How can you merge objects in array of objects?

前端 未结 12 1237
小蘑菇
小蘑菇 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 17:58

    Short way with array reduce:

    const arrayOfObjects = [
     {name: "name1", surname: "surname1"}, {name: 'Anne', surname: 'Example'}, {name: 'name3', surname: 'Example3'}
    ];
    /*
    {name: ['Fred', 'Anne'], surname: ['Example', 'Shultz']}
    */
    var result = arrayOfObjects.reduce((obj,current)=>{
        (obj['name'] = obj['name']||[]).push(current.name);
        (obj['surname'] = obj['surname']||[]).push(current.surname);
        return obj;
    },{});
    console.log(result);

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-12-06 18:00

    The following should work - uses a few ES6 helpers, but the key is Array#reduce which is in ES5.

    const result = arrayOfObjects.reduce((acc, obj) => {
        for (let key in obj) {
            if (key in acc) {
                acc[key].push(obj[key]);
            }
            else {
                acc[key] = [obj[key]];
            }
        }
        return acc;
    }, {});
    
    0 讨论(0)
  • 2020-12-06 18:03

    You can use lodash's mergeWith like so:

    const result = _.mergeWith({}, ...arrayOfObjects, (value, objValue) =>
        (value || []).concat(objValue)
    );
    

    Example:

    const arrayOfObjects = [
        {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
    ];
    
    const result = _.mergeWith({}, ...arrayOfObjects, (value, objValue) =>
        (value || []).concat(objValue)
    );
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

    0 讨论(0)
  • 2020-12-06 18:03

    Here is a lodash approach

      _(input).flatMap(_.entries).groupBy(0).mapValues(v => _.map(v, 1)).value()
    

    var input = [
     {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
    ];
    
    var res =   _(input).flatMap(_.entries).groupBy(0).mapValues(v => _.map(v, 1)).value()
    
    console.log(res);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    This will take care if the objects doesn't have exactly same key sets

    0 讨论(0)
  • 2020-12-06 18:04

    This is one abroach of implementation details, written in fairly easy to understand and readable manner.

    https://codesandbox.io/s/r7x16j950n

    const arrayOfObjects = [
      { name: "Fred", surname: "Shultz" },
      { name: "Anne", surname: "Example" }
    ];
    
    let obj = {};
    
    arrayOfObjects.forEach(row => {
      Object.keys(row).forEach(key => {
        obj[key] = !obj[key]
          ? [row[key]]
          : [...obj[key], row[key]];
      });
    });
    
    console.log(obj);
    
    0 讨论(0)
提交回复
热议问题