我目前有以下数据结构:
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};
});
但是我有点迷茫,你有什么建议吗?
Array.map
还是新的 ES6Map
结构?似乎有些混淆。因为如果你想要后者,你可以直接这样做:bar.reduce((m, o) => m.set(o.id, o), new Map());
。Array.map
早在 ES6 之前就已经存在了。 - Andynew Map(Object.entries(bar));
- @安迪 -new Map(Object.entries(bar));
- Ori Drori