What is the simplest solution to flat a JavaScript array of objects into an object?


Flat array of objects into an object, you can use the concept of reduce(). Let’s say following is our array of objects −

const studentDetails = [
   {Name: "Chris"},
   {Age: 22}
]

Example

const studentDetails = [
   {Name: "Chris"},
   {Age: 22}
]
const objectStudent = studentDetails.reduce((obj, value) => {
   return { ...obj, ...value }
}, {})
console.log(objectStudent);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo64.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo64.js
{ Name: 'Chris', Age: 22 }

Updated on: 03-Sep-2020

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements