w3resource

JavaScript: Create a new object from the combination of two or more objects

JavaScript fundamental (ES6 Syntax): Exercise-178 with Solution

Write a JavaScript program to create a new object from the combination of two or more objects.

  • Use Array.prototype.reduce() combined with Object.keys() to iterate over all objects and keys.
  • Use Object.prototype.hasOwnProperty() and Array.prototype.concat() to append values for keys existing in multiple objects.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const merge = (...objs) =>
  [...objs].reduce(
    (acc, obj) =>
      Object.keys(obj).reduce((a, k) => {
        acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
        return acc;
      }, {}),
    {}
  );
const object = {
  a: [{ x: 2 }, { y: 4 }],
  b: 1
};
const other = {
  a: { z: 3 },
  b: [2, 3],
  c: 'foo'
};
console.log(merge(object, other));

Sample Output:

{"a":[{"x":2},{"y":4},{"z":3}],"b":[1,2,3],"c":"foo"}

Flowchart:

flowchart: Create a new object from the combination of two or more objects

Live Demo:

See the Pen javascript-basic-exercise-178-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get the minimum value of an array, after mapping each element to a value using the provided function.
Next: Write a JavaScript program to compare two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.