How can you merge objects in array of objects?

前端 未结 12 1284
小蘑菇
小蘑菇 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: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);

提交回复
热议问题