将JS对象数组转换为嵌套形式的最有效方法?

时间:2016-05-02 20:47:58

标签: javascript arrays normalization

我想改造:

[
    {id: 1, name: 'one', desc: 'one'},
    {id: 2, name: 'two', desc: 'two'},
    {id: 3, name: 'three', desc: 'three'}
]

{
    1: {id: 1, name: 'one', desc: 'one'},
    2: {id: 2, name: 'two', desc: 'two'},
    3: {id: 3, name: 'three', desc: 'three'}
}

最有效/最佳的方式是什么?一些选项是:

1)https://github.com/gaearon/normalizr

2)d3.nest()

3)const object = {}; array.forEach(item => { object[item.id] = item });

4 个答案:

答案 0 :(得分:1)

我喜欢Array.prototype.reduce()解决方案。看看这个



var arr = [{id: 1, name: 'one', desc: 'one'}, {id: 2, name: 'two', desc: 'two'}, {id: 3, name: 'three', desc: 'three'}],
    obj = arr.reduce((p,c) => {p[c.id] = c; return p},{});

document.write("<pre>" + JSON.stringify(obj,null,2) + "</pre>");
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您还可以使用简单的循环:

var arr = [{id: 1, name: 'one', desc: 'one'}, {id: 2, name: 'two', desc: 'two'}, {id: 3, name: 'three', desc: 'three'}],
    obj = {}
for(var item of arr) obj[item.id] = item;

通常循环比ES5数组方法更快,因为它们不必在每次迭代时调用函数。

答案 2 :(得分:0)

我会说它是:

const obj = Object.assign( {}, array );

虽然,我没有将其表现与您的选择进行比较。

答案 3 :(得分:0)

试试这个:

&#13;
&#13;
ar = [
    {id: 1, name: 'one', desc: 'one'},
    {id: 2, name: 'two', desc: 'two'},
    {id: 3, name: 'three', desc: 'three'}
]

var result = ar.reduce((ac, x) => {return ac[x.id] = x , ac ;}, {})

document.write( JSON.stringify(result) )
&#13;
&#13;
&#13;

但请记住,键是字符串,你处理的是一个不是数组的对象......