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
Formatting dynamic json array JavaScript
Let's say, we have an array of objects like this -
const arr = [
{"name1": "firstString"},
{"name2": "secondString"},
{"name3": "thirdString"},
{"name4": "fourthString"},
{"name5": "fifthString"},
{"name6": "sixthString"},
];
We are required to write a function that takes one such array of objects and returns an object with all the properties listed in that object.
So, let's write the code for this function. It can be done through the Array reduce method -
Using Array.reduce() Method
const arr = [
{"name1": "firstString"},
{"name2": "secondString"},
{"name3": "thirdString"},
{"name4": "fourthString"},
{"name5": "fifthString"},
{"name6": "sixthString"},
];
const reduceArray = arr => {
return arr.reduce((acc, val) => {
Object.assign(acc, val);
return acc;
}, {});
};
console.log(reduceArray(arr));
{
name1: 'firstString',
name2: 'secondString',
name3: 'thirdString',
name4: 'fourthString',
name5: 'fifthString',
name6: 'sixthString'
}
Alternative Using Spread Operator
You can also achieve the same result using the spread operator with reduce:
const arr = [
{"name1": "firstString"},
{"name2": "secondString"},
{"name3": "thirdString"}
];
const mergeObjects = arr => {
return arr.reduce((acc, obj) => ({...acc, ...obj}), {});
};
console.log(mergeObjects(arr));
{
name1: 'firstString',
name2: 'secondString',
name3: 'thirdString'
}
How It Works
The reduce() method iterates through each object in the array and merges it into an accumulator object. Object.assign() copies all properties from the current object to the accumulator, effectively flattening the array of objects into a single object.
Conclusion
Both approaches effectively merge an array of objects into a single object. The Object.assign() method modifies the accumulator directly, while the spread operator creates a new object on each iteration.
