How can you merge objects in array of objects?

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

提交回复
热议问题