Convert an array of objects into plain object in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
}
raja
Published on 18-Jan-2021 09:14:38
Advertisements