Convert an array of objects into plain object in JavaScript


Suppose we have an array of objects like this −

const arr = [{
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
}, {
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
}];

We are required to write a JavaScript function that takes in one such array of objects. The function should then prepare an object that contains all the properties that exist in all the objects of the array.

Therefore, for the above array, the output should look like −

const output = {
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
};

Example

Following is the code −

const arr = [{
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
}, {
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
}];
const mergeObjects = (arr = []) => {
   const res = {};
   arr.forEach(obj => {
      for(key in obj){
         res[key] = obj[key];
      };
   });
   return res;
};
console.log(mergeObjects(arr));

Output

Following is the console output −

{
   name: 'Dinesh Lamba',
   age: 23,
   occupation: 'Web Developer',
   address: 'Vasant Vihar',
   experience: 5,
   isEmployed: true
}

Updated on: 18-Jan-2021

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements