Merge objects in a loop

Viewed 442

I have this array of arrays of objects :

[
  [
    {a: 'FER', b: 'MEN', c: 'TUM'},
    {a: 'RIS ', b: 'US', c: 'SOU'}, 
    {a: 'CON', b: 'SEC', c: 'TETUR'}
  ],
  [
    {d: 'LIGU'}, 
    {d: 'GU'}, 
    {d: 'LA'}
  ],
  [
    {e: 'UL', f: 'LAM'},
    {e: 'COR', f: 'PER'},
    {e: 'EGE', f: 'STAS'}
  ]
]

What I want to obtain in the more generic manner is this (in reality, I have one array of 21 arrays with 205 objects in each):

[
  {a: 'FER', b: 'MEN', c: 'TUM', d: 'LIGU', e: 'UL', f: 'LAM'},
  {a: 'RIS ', b: 'US', c: 'SOU', d: 'GU', e: 'COR', f: 'PER'},
  {a: 'CON', b: 'SEC', c: 'TETUR', d: 'LA', e: 'EGE', f: 'STAS'}
]

I tried so many things (object assign, reduce, etc.) but my head is a mess right now and I'm stuck on how I can merge objects in a loop. Any help so much appreciated!

3 Answers

You could reduce with a mapping of objects.

const
    data = [[{ a: 'FER', b: 'MEN', c: 'TUM' }, { a: 'RIS ', b: 'US', c: 'SOU' }, { a: 'CON', b: 'SEC', c: 'TETUR' }], [{ d: 'LIGU' }, { d: 'GU' }, { d: 'LA' }], [{ e: 'UL', f: 'LAM' }, { e: 'COR', f: 'PER' }, { e: 'EGE', f: 'STAS' }]],
    result = data.reduce((a, b) => a.map((o, i) => ({ ...o, ...b[i] })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Using Array#reduce and Array#forEach:

const data = [
  [
    { a: 'FER', b: 'MEN', c: 'TUM' },
    { a: 'RIS ', b: 'US', c: 'SOU' }, 
    { a: 'CON', b: 'SEC', c: 'TETUR' }
  ],
  [
    { d: 'LIGU' }, 
    { d: 'GU' }, 
    { d: 'LA' }
  ],
  [
    { e: 'UL', f: 'LAM' },
    { e: 'COR', f: 'PER' },
    { e: 'EGE', f: 'STAS' }
  ]
];

const res = data.reduce((acc, arr) => {
  arr.forEach((obj, i) => {
    acc[i] = { ...(acc[i] || {}), ...obj };
  });
  return acc;
}, []);

console.log(res);

var counter = 0,
    finalarr = [],
    tmpobj = {};
while (counter < arr[0].length) {
    tmpobj = {}
    arr.forEach((subarr, index) => {
        tmpobj = {
            ...tmpobj,
            ...subarr[counter]
        }
    })
    finalarr.push(tmpobj)

    counter++;
}
console.log('Final array:', finalarr)
Related