How to concatenate two JavaScript objects with plain JavaScript ?


Suppose we have two objects defined like this −

const obj1 = {
   id1: 21,
   name1: "Kailash"
};
const obj2 = {
   id2: 20,
   name2: "Shankar"
};

We are required to write a JavaScript function that takes in two such objects and merges into a single object.

In other words, we are required to more or less implement the functionality of Object.assign() function.

Example

The code for this will be −

const obj1 = {
   id1: 21,
   name1: "Kailash"
};
const obj2 = {
   id2: 20,
   name2: "Shankar"
};
const concatObjects = (...sources) => {
   const target = {};
   sources.forEach(el => {
      Object.keys(el).forEach(key => {
         target[key] = el[key];
      });
   });
   return target;
}
console.log(concatObjects(obj1, obj2));

Output

And the output in the console will be −

{ id1: 21, name1: 'Kailash', id2: 20, name2: 'Shankar' }

Updated on: 21-Nov-2020

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements