使用es6 map

时间:2017-09-26 16:26:35

标签: javascript arrays ecmascript-6

我目前有以下数据结构:

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 个答案:

答案 0 :(得分:3)

您可以将reduce()Object.assign()

一起使用

&#13;
&#13;
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)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以将Object.assignArray#mapspread syntax ...

一起使用

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; }

答案 2 :(得分:1)

application:continueUserActivity:restorationHandler:返回一个数组,如果你想返回一个对象,你可以使用Array.map代替

Array.reduce

如果您只需要重新格式化数据以将其发送到API,则无需使用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);

创建对象的真实克隆

答案 3 :(得分: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}, {});

答案 4 :(得分:1)

另一种方法可能是使用迭代数组的forEach,但不会像map那样返回数组:

let foo = {};
bar.forEach((el, idx) => foo[idx+1] = el)