【问题标题】:javascript create an object with key obtained from value of a key from another array of objectsjavascript 创建一个对象,其键是从另一个对象数组的键的值中获得的
【发布时间】:2018-03-12 11:26:53
【问题描述】:

我正在从对象数组中创建一个对象,使用其中一个键的值:

const myArray = [
  {
    uuid: '123',
    name: 'abc'
  },
  {
    uuid: '789',
    name: 'xyz'
  }    
];

const newObj = {};
for (var i = 0; i < myArray.length; i++) {
    newObj[myArray[i].uuid] = myArray[i];
}

console.log('result: ', newObj)

如何使用 ecma6 实践做同样的事情?

【问题讨论】:

  • 您可以在数组上使用forEach(这在 ES5 中也可以使用)。基本 JavaScript 就是这样。

标签: javascript arrays ecmascript-6


【解决方案1】:

使用函数reduceSpread syntaxComputed property namesArrow functions

const myArray = [  {    uuid: '123',    name: 'abc'  },  {    uuid: '789',    name: 'xyz'  }    ];

var newObj = myArray.reduce((a, c) => ({...a, [c.uuid]: c}), {});
console.log('result: ', newObj)
.as-console-wrapper { max-height: 100% !important; top: 0; }

资源

【讨论】:

    【解决方案2】:

    您可以将Object.assign()map() 一起使用并传播语法...

    const myArray = [{uuid: '123',name: 'abc'},{uuid: '789',name: 'xyz'}];
    
    const newObj = Object.assign({}, ...myArray.map(e => ({[e.uuid]: e})))
    console.log(newObj)

    【讨论】:

      【解决方案3】:

      其他答案很花哨,但我认为最易读、最简单的答案如下:

      const myArray = [{uuid: '123',name: 'abc'},{uuid: '789',name: 'xyz'}];
      
      const newObj = {}
      myArray.forEach(item => newObj[item.uuid] = item)
      
      console.log(newObj)

      是的,这在第 5 版中可用,但我认为适用于问题的目标。

      【讨论】:

        猜你喜欢
        • 2015-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        • 2023-01-08
        • 2018-02-13
        相关资源
        最近更新 更多