javascript使用从另一个对象数组中的键值获得的键创建一个对象

时间:2018-03-12 00:38:05

标签: javascript arrays ecmascript-6

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



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

我怎样才能使用ecma6做法?

3 个答案:

答案 0 :(得分:2)

使用功能reduceSpread syntaxComputed property namesArrow functions

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

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

资源

答案 1 :(得分:2)

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

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

const newObj = Object.assign({}, ...myArray.map(e => ({[e.uuid]: e})))
console.log(newObj)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

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

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

const newObj = {}
myArray.forEach(item => newObj[item.uuid] = item)

console.log(newObj)
&#13;
&#13;
&#13;

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