How can you merge objects in array of objects?

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

提交回复
热议问题