0

I have an array of objects. Want to make one universal object, with all possible keys and values like in resultObj.

  let arr = [
          { "11": [ 19,20 ], "12": [ 21, 22, 24], "13": [ 25, 27 ]}
          { "11": [ 19,30 ], "12": [ 22, 23], "13": [ 25, 26, 27 ], "14": [ 28, 29 ]}
          { "11": [ 19,20,30 ], "12": [ 21, 23], "13": [ 26 ], "15": [ 31, 32, 33 ]}
    ]

let resultObj = {"11": [ 19,20,30 ], "12": [ 21, 22, 23, 24], "13": [ 25, 26, 27 ], "14": [ 28, 29 ], "15": [ 31, 32, 33 ]}
  • 2
    Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) – Simone Rossaini Jul 22 '22 at 12:43

2 Answers2

2
  1. loop over all items in the array
  2. loop over each value in the key array
  3. set them to their key in the reduced object, avoid duplicates by using a Set
const arr = [
  { 11: [19, 20], 12: [21, 22, 24], 13: [25, 27] },
  { 11: [19, 30], 12: [22, 23], 13: [25, 26, 27], 14: [28, 29] },
  { 11: [19, 20, 30], 12: [21, 23], 13: [26], 15: [31, 32, 33] },
];

const result = arr.reduce((accumulator, currentValue) => {
  Object.entries(currentValue).forEach(([key, value]) => {
    accumulator[key] = [...new Set([...(accumulator[key] || []), ...value])];
  });
  return accumulator;
}, {});

// {
//   '11': [19, 20, 30],
//   '12': [21, 22, 24, 23],
//   '13': [25, 27, 26],
//   '14': [28, 29],
//   '15': [31, 32, 33],
// };
marcobiedermann
  • 4,317
  • 3
  • 24
  • 37
1

You can use this code :

let arr = [
    { "11": [ 19,20 ], "12": [ 21, 22, 24], "13": [ 25, 27 ]},
    { "11": [ 19,30 ], "12": [ 22, 23], "13": [ 25, 26, 27 ], "14": [ 28, 29 ]},
    { "11": [ 19,20,30 ], "12": [ 21, 23], "13": [ 26 ], "15": [ 31, 32, 33 ]},
]

let keys = [...new Set(arr.flatMap(obj => Object.keys(obj)))];

let result = Object.fromEntries(
    keys.map(k => [k, [...new Set(arr.map(obj => obj[k] ).filter(obj => obj).flat())]])
);

console.log(result);
nem0z
  • 1,060
  • 1
  • 4
  • 17