我正在使用其中一个键的值从对象数组创建一个对象:
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;
我怎样才能使用ecma6做法?
答案 0 :(得分:2)
使用功能reduce
,Spread syntax
,Computed property names
和Arrow 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)
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分: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)
&#13;
答案 2 :(得分:0)
其他答案很花哨,但我认为最可读,最简单的答案如下:
const myArray = [{uuid: '123',name: 'abc'},{uuid: '789',name: 'xyz'}];
const newObj = {}
myArray.forEach(item => newObj[item.uuid] = item)
console.log(newObj)
&#13;
是的,这在版本5中可用,但我认为适用于问题的目标。