javascript - JS adds multiple dynamic properties to objects
仅有的幸福
仅有的幸福 2017-06-26 10:51:28
0
5
880
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?

仅有的幸福
仅有的幸福

reply all(5)
小葫芦
arr.reduce((prev, curr) => Object.assign(prev, curr), {})
小葫芦
arr.reduce((prev, next) => {
    Object.keys(next).forEach((item) => {
         prev[item] = next[item]        
    })
    return prev
}, {})
代言

@冴宇 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.

给我你的怀抱

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)

洪涛

Question and answer first, use Object.assign() to merge, I don’t know if there are other good methods

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template