How can you merge objects in array of objects?

前端 未结 12 1317
小蘑菇
小蘑菇 2020-12-06 17:32

I\'m looking for the best solution to merge all objects in one array

const arrayOfObjects = [
 {name: \'Fred\', surname: \'Shultz\'}, {name: \'Anne\', surnam         


        
12条回答
  •  暖寄归人
    2020-12-06 18:00

    If the arrayOfObjects is set on these 2 props then it is as simple as:

    const data = [{ name: 'Fred', surname: 'Shultz' }, { name: 'Anne', surname: 'Example' }]
    
    const r = data.reduce((r,c) => 
       (r.name.push(c.name), r.surname.push(c.surname),r), {name:[], surname:[]})
    
    console.log(r)

    One reduce with an accumulator of {name:[], surname:[]} to be filled.

    If you need to be more generic and work for any set of objects:

    const data = [{
      name: 'Fred',
      surname: 'Shultz'
    },{
      name: 'Anne',
      surname: 'Example'	
    },{
      name: 'John',
      position: 'Dev' // <--- Notice different prop
    }]
    
    const result = data.reduce((r,c) => 
      (Object.keys(c).map(k => r[k] = [...r[k] || [], c[k]]), r), {})
    
    console.log(result)

    Again is just a reduce with Object.keys to do the job.

    Note both approaches utilize ES6 arrow functions, array destricturing and (for the 2nd one) combining multiple operations via enclosing them in parentheses (op1,op2)

提交回复
热议问题