How can you merge objects in array of objects?

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

提交回复
热议问题