- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements