JavaScript Union of two objects


We have one object like this −

const obj1 = { name: " ", email: " " };

and another like this −

const obj2 = { name: ['x'], email: ['y']};

We are required to write a JavaScript function that takes in two such objects. and want the output to be the union like this −

const output = { name: {" ", [x]}, email: {" ", [y]} };

Example

The code for this will be −

const obj1 = { name: " ", email: " " };
const obj2 = { name: ['x'], email: ['y']};
const objectUnion = (obj1 = {}, obj2 = {}) => {
   const obj3 = {
      name:[],
      email:[]
   };
   for(let i in obj1) {
      obj3[i].push(obj1[i]);
   }
   for(let i in obj2) {
      obj3[i].push(obj2[i]);
   }
   return obj3;
};
console.log(objectUnion(obj1, obj2));

Output

And the output in the console will be −

{ name: [ ' ', [ 'x' ] ], email: [ ' ', [ 'y' ] ] }

Updated on: 24-Nov-2020

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements