Home > Software design >  create universal Object
create universal Object

Time:07-23

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 ]}

CodePudding user response:

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);

CodePudding user response:

  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],
// };
  • Related