【问题标题】:Most efficient way to transform array of JS objects to nested form?将 JS 对象数组转换为嵌套形式的最有效方法?
【发布时间】:2016-08-27 17:56:34
【问题描述】:

我要变身:

[
    {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 });

【问题讨论】:

  • 你已经在那个配置中有一个对象,只是它从 0 而不是 1 开始。;-)

标签: javascript arrays normalization


【解决方案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】:

    试试这个:

    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) )

    但请记住,键是字符串,并且您处理的是对象而不是数组...

    【讨论】:

      【解决方案3】:

      我喜欢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>");

      【讨论】:

        【解决方案4】:

        我会说它是:

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

        虽然,我没有将它的性能与您的选择进行比较。

        【讨论】:

        • 那行不通,OP 想通过.id 分配它们,而不是通过它们在数组中的索引。
        猜你喜欢
        • 1970-01-01
        • 2021-04-21
        • 2018-01-04
        • 1970-01-01
        • 2021-07-12
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多