[英]javascript create an object with key obtained from value of a key from another array of objects
I am creating an object from the array of objects, using the value for one of the keys: 我正在使用键之一的值从对象数组创建一个对象:
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)
how can I do the same using ecma6 practices? 如何使用ecma6做法做同样的事情?
Using the functions reduce
, Spread syntax
, Computed property names
and Arrow functions
. 使用函数
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)
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use Object.assign()
with map()
and spread syntax ...
您可以将
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)
The other answers are fancy, but I think the most readable, and simplest answer is the following: 其他答案都不错,但是我认为最容易理解和最简单的答案如下:
const myArray = [{uuid: '123',name: 'abc'},{uuid: '789',name: 'xyz'}]; const newObj = {} myArray.forEach(item => newObj[item.uuid] = item) console.log(newObj)
Yes this was available in version 5, but I think is applicable to the goal of the question. 是的,这在版本5中可用,但我认为适用于该问题的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.