Syntax error How to merge two object arrays of different size by key in JavaScript

How to merge two object arrays of different size by key in JavaScript



Suppose, we have an object like this −

const obj = {
   "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}],
   "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}]
};

We are required to write a JavaScript function that takes in one such object. The function should merge part1 and part2 of the object to form an array of objects like this −

const output = [
   {"id": 1, "a": 50, "b": 40},
   {"id": 2, "a": 55},
   {"id": 3, "b": 45},
   {"id": 4, "a": 100, "b": 110}
];

Example

The code for this will be −

const obj = {
   "part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}],
   "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}]
};
const mergeObject = (obj = {}) => {
   let result = [];
   result = Object.keys(obj).reduce(function (hash) {
      return function (r, k) {
         obj[k].forEach(function (o) {
            if (!hash[o.id]) {
               hash[o.id] = {};
               r.push(hash[o.id]);
            }
            Object.keys(o).forEach(function (l) {
               hash[o.id][l] = o[l];
            });
         });
         return r;
      };
   }(Object.create(null)), []).sort((a, b) => {
      return a['id'] − b['id'];
   });
   return result;
};
console.log(mergeObject(obj));

Output

And the output in the console will be −

[
   { id: 1, a: 50, b: 40 },
   { id: 2, a: 55 },
   { id: 3, b: 45 },
   { id: 4, a: 100, b: 110 }
]
Updated on: 2020-11-20T13:52:02+05:30

801 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements