使用ES6的map将数组转换为对象

3

我目前有以下数据结构:

const bar = [
    {id:1, version:0, name:"test name A"},
    {id:2, version:0, name:"test name B"},
    {id:3, version:0, name:"test name C"}
];

我需要将其转换为这样:

const foo = {
    1:{id:1, version:0, name:"test name A"},
    2:{id:2, version:0, name:"test name B"},
    3:{id:3, version:0, name:"test name C"}
};

我现有的代码如下:

for(let i=0;len = bar.length; i< len;i++){
    foo[bar[i].id]= bar[i];
}

我已经尝试过

bar.map((element,index)=>{
    const temporal = {[index]:element};
    foo = {...foo, temporal};
});

但是我有点迷茫,你有什么建议吗?

5
为什么你希望拥有一个带有数字索引的对象? - adeneo
1
你是在说使用 Array.map 还是新的 ES6 Map 结构?似乎有些混淆。因为如果你想要后者,你可以直接这样做:bar.reduce((m, o) => m.set(o.id, o), new Map());Array.map 早在 ES6 之前就已经存在了。 - Andy
3
@Andy - new Map(Object.entries(bar)); - @安迪 - new Map(Object.entries(bar)); - Ori Drori
@adeneo 我不想这样做。这是一个我需要传递给API的数据结构。 - Anyul Rivas
2
@OriDrori,哈!正如你所猜测的那样,我对你之前的代码印象深刻。感谢你让我保持警惕。顺便说一句,你之前的回答非常出色。 - Andy
5个回答

4
您可以使用 reduce() Object.assign()

const bar = [
    {id:1, version:0, name:"test name A"},
    {id:2, version:0, name:"test name B"},
    {id:3, version:0, name:"test name C"}
];

var result = bar.reduce((r, e) => Object.assign(r, {[e.id]: e}), {});
console.log(result)


2
您可以使用Object.assignArray#map,以及展开语法...来进行操作。请注意保留HTML标签。

const
    bar = [{ id: 1, version: 0, name: "test name A" }, { id: 2, version: 0, name: "test name B" }, { id: 3, version: 0, name: "test name C" }],
    object = Object.assign(...bar.map(o => ({ [o.id]: o })));

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }


1
您可以使用reduce,也称为折叠或通用注入:
const bar = [
    {id:1, version:0, name:"test name A"},
    {id:2, version:0, name:"test name B"},
    {id:3, version:0, name:"test name C"}
];

bar.reduce((obj, e, i) => { obj[e.id] = e; return obj}, {});

1

Array.map 返回一个数组,如果你想返回一个对象,可以使用 Array.reduce

const bar = [
    {id:1, version:0, name:"test name A"},
    {id:2, version:0, name:"test name B"},
    {id:3, version:0, name:"test name C"}
];

var foo = bar.reduce( (a,b,i) => (a[i+1] = b, a), {});

console.log(foo);

如果您只需要重新格式化数据以将其发送到API,那么没有必要使用Object.assign创建对象的真正克隆。

1
另一种方法可以使用forEach,它遍历数组,但不像map那样返回一个数组:
let foo = {};
bar.forEach((el, idx) => foo[idx+1] = el)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接