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
How to transform object of objects to object of array of objects with JavaScript?
To transform an object of objects into an object of array of objects, you can use Object.fromEntries() along with Object.entries() and map(). This transformation wraps each nested object in an array while preserving the original keys.
Syntax
Object.fromEntries(
Object.entries(originalObject).map(([key, value]) => [key, [value]])
)
Example
const studentDetails = {
'details1': {Name: "John", CountryName: "US"},
'details2': {Name: "David", CountryName: "AUS"},
'details3': {Name: "Bob", CountryName: "UK"},
};
const transformedObject = Object.fromEntries(
Object.entries(studentDetails).map(([key, value]) => [key, [value]])
);
console.log(transformedObject);
{
details1: [ { Name: 'John', CountryName: 'US' } ],
details2: [ { Name: 'David', CountryName: 'AUS' } ],
details3: [ { Name: 'Bob', CountryName: 'UK' } ]
}
How It Works
The transformation process involves three steps:
-
Object.entries()converts the object into an array of [key, value] pairs -
map()transforms each pair by wrapping the value in an array:[key, [value]] -
Object.fromEntries()converts the array of pairs back into an object
Step-by-Step Breakdown
const studentDetails = {
'details1': {Name: "John", CountryName: "US"},
'details2': {Name: "David", CountryName: "AUS"}
};
// Step 1: Convert to entries
const entries = Object.entries(studentDetails);
console.log("Step 1 - Entries:", entries);
// Step 2: Map to wrap values in arrays
const mappedEntries = entries.map(([key, value]) => [key, [value]]);
console.log("Step 2 - Mapped:", mappedEntries);
// Step 3: Convert back to object
const result = Object.fromEntries(mappedEntries);
console.log("Step 3 - Final:", result);
Step 1 - Entries: [
[ 'details1', { Name: 'John', CountryName: 'US' } ],
[ 'details2', { Name: 'David', CountryName: 'AUS' } ]
]
Step 2 - Mapped: [
[ 'details1', [ { Name: 'John', CountryName: 'US' } ] ],
[ 'details2', [ { Name: 'David', CountryName: 'AUS' } ] ]
]
Step 3 - Final: {
details1: [ { Name: 'John', CountryName: 'US' } ],
details2: [ { Name: 'David', CountryName: 'AUS' } ]
}
Common Use Cases
This transformation is useful when you need to:
- Prepare data for APIs that expect arrays of objects
- Convert single objects to arrays for consistent data processing
- Normalize data structures for array methods like
forEach()orfilter()
Conclusion
Using Object.fromEntries() with Object.entries() and map() provides a clean, functional approach to transform objects of objects into objects of arrays. This method preserves the original structure while wrapping each value in an array.
Advertisements
