search

Home  >  Q&A  >  body text

javascript - JS adds multiple dynamic properties to objects

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?

仅有的幸福仅有的幸福2777 days ago891

reply all(5)I'll reply

  • 高洛峰

    高洛峰2017-06-26 10:53:28

    arr.reduce((prev, curr) => Object.assign(prev, curr), {})

    reply
    0
  • 高洛峰

    高洛峰2017-06-26 10:53:28

    arr.reduce((prev, next) => {
        Object.keys(next).forEach((item) => {
             prev[item] = next[item]        
        })
        return prev
    }, {})

    reply
    0
  • 代言

    代言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.

    reply
    0
  • 给我你的怀抱

    给我你的怀抱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)

    reply
    0
  • PHP中文网

    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

    reply
    0
  • Cancelreply