Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the simplest solution to flat a JavaScript array of objects into an object?
Flattening an array of objects into a single object combines all key-value pairs from the array elements. The simplest solution uses the reduce() method with the spread operator.
Problem Example
Consider an array of objects where each object contains different properties:
const studentDetails = [
{Name: "Chris"},
{Age: 22}
];
console.log("Original array:", studentDetails);
Original array: [ { Name: 'Chris' }, { Age: 22 } ]
Using reduce() with Spread Operator
The reduce() method iterates through the array and combines all objects into one:
const studentDetails = [
{Name: "Chris"},
{Age: 22},
{City: "New York"}
];
const flattenedObject = studentDetails.reduce((obj, value) => {
return { ...obj, ...value };
}, {});
console.log(flattenedObject);
{ Name: 'Chris', Age: 22, City: 'New York' }
How It Works
The reduce() method:
- Starts with an empty object
{}as the initial accumulator - For each array element, spreads both the accumulator and current object
- Returns a new object containing all combined properties
Handling Duplicate Keys
When objects have the same property names, later values override earlier ones:
const data = [
{name: "John", age: 25},
{name: "Jane", city: "Boston"},
{age: 30}
];
const result = data.reduce((obj, value) => {
return { ...obj, ...value };
}, {});
console.log(result);
{ name: 'Jane', age: 30, city: 'Boston' }
Alternative: Object.assign()
You can also use Object.assign() for the same result:
const studentDetails = [
{Name: "Chris"},
{Age: 22}
];
const flattenedObject = Object.assign({}, ...studentDetails);
console.log(flattenedObject);
{ Name: 'Chris', Age: 22 }
Conclusion
Use reduce() with spread operator to flatten arrays of objects into single objects. This method is clean, readable, and handles duplicate keys by keeping the last occurrence.
Advertisements
