let Obj={};
//给出一个数组
var arr = [
{a: 'aa'},
{b: 'bb'},
{c: 'cc'}
]
//生成如下格式
Obj={
a:'aa',
b:'bb',
c:'cc'
}
Personally, I think you can use Object.assign() to merge. Is there any other good method?
高洛峰2017-06-26 10:53:28
arr.reduce((prev, next) => {
Object.keys(next).forEach((item) => {
prev[item] = next[item]
})
return prev
}, {})
代言2017-06-26 10:53:28
@冴宇 and @cool_zjy’s solutions are similar, but they both generate a new object. According to the original question, the initial value of reduce
is passed into Obj
instead of {}
. The former does not require ES6 features, the latter does.
@hsfzxjy’s method seems to be simple, but it will generate a lot of intermediate objects, so the efficiency should not be very good.
Object.assign
should be the simplest solution. Of course, maybe a simpler API can be found in the Lodash library to implement it.
给我你的怀抱2017-06-26 10:53:28
Laxative. Using the ES6 Spread Operator can be more concise, but the essence is the same
let arr = [
{a: 'aa'},
{b: 'bb'},
{c: 'cc'}
]
let obj = arr.reduce((x, y) => ({...x, ...y}), {})
console.log(obj)
PHP中文网2017-06-26 10:53:28
Question and answer first, use Object.assign() to merge, I don’t know if there are other good methods