How can you merge objects in array of objects?

前端 未结 12 1238
小蘑菇
小蘑菇 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:07

    easy with lodash:

    grouped = _.mapValues(arrayOfObjects[0], 
        (val, key) => _.map(arrayOfObjects, key))
    

    pure es6

    let grouped = {};
    
    for (let obj of arrayOfObjects)
        for (let [key, val] of Object.entries(obj))
            grouped[key] = (grouped[key] || []).concat(val)
    

    if the keys differ from item to item, you could use something like this to collect them all:

    grouped = _(arrayOfObjects)
        .flatMap(_.entries)
        .groupBy(0)
        .mapValues(x => _.map(x, 1))
        .value()
    
    0 讨论(0)
  • 2020-12-06 18:09

    Don't make it any more complicated than it needs to be:

    const arrayOfObjects = [
        {name: 'Fred', surname: 'Shultz'},
        {name: 'Anne', surname: 'Example'}
    ];
    
    const result = {name:[], surname:[]};
    for (const obj of arrayOfObjects)
        for (const prop in result)
            result[prop].push(obj[prop]);
    

    I will assume that you statically know the property names that your result should have - one can't really do it dynamically anyway as that wouldn't work properly for an empty input array.

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

    You could reduce the array by iterating the entries and collecting the values, depending of the keys.

    const
        array = [{ name: 'Fred', surname: 'Shultz' }, { name: 'Anne', surname: 'Example' }],
        result = array.reduce((r, o) => {
            Object.entries(o).forEach(([k, v]) => (r[k] = r[k] || []).push(v));
            return r;
        }, Object.create(null));
    
    console.log(result);

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

    Without any library

    const mergeObjectInArray=(input)=>{
    const myObj={};
    Object.keys(input[0]).forEach(key=>myObj[key]=input.map(inp=>inp[key]));
    return myObj;
    }
    
    0 讨论(0)
  • 2020-12-06 18:21

    You could do it like this:

    const arrayOfObjects = [
      {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
    ];
    
    const result = {};
    arrayOfObjects.forEach(item => {
      Object.keys(item).forEach(key => {
        if (!result[key]) {
          result[key] = [];
        }
        result[key].push(item[key]);
      });
    });
    
    console.log(result);

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

    with pure javascript

    var myInput = [{ a: 1, b: 2, c: 3 }, { a: 2, b: 4, c: 6 }, { a: 7, b: 8, c: 9 }];
        var myArray = [];
        var myObject = {};
        function isArray(a){
            return Object.prototype.toString.call(a) === '[object Array]' ;
        }
        for (var i = 0; i < myInput.length; i++) {
            for (var key in myInput[i]) {
                if (myInput[i].hasOwnProperty(key)) {
                    if (myArray.indexOf(key) === -1) {
                        myArray.push(key);
                        myObject[key] = myInput[i][key];
                    } else {
                        if (myObject.hasOwnProperty(key)) {
                            newary = [];
                            if (isArray(myObject[key])) {
                                for (var i = 0; i < myObject[key].length; i++) {
                                    newary.push(myObject[key][i]);
                                }
                            } else {
                                newary.push(myObject[key]);
                            }
                            newary.push(myInput[i][key]);
                            myObject[key] = newary;
                        }
                    }
                }
            }
        }
        console.log(myObject);

    0 讨论(0)
提交回复
热议问题