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
Un-nesting array of object in JavaScript?
To un-nest an array of objects in JavaScript, you can use the map() method to restructure nested data into a flatter format. This is useful when you have deeply nested objects and want to extract specific properties to create a simpler structure.
Problem: Nested Object Structure
Let's say you have an array of student objects where subject details are nested inside each student:
const studentDetails = [
{
"studentId": 101,
"studentName": "John",
"subjectDetails": {
"subjectName": "JavaScript"
}
},
{
"studentId": 102,
"studentName": "David",
"subjectDetails": {
"subjectName": "MongoDB"
}
}
];
console.log("Original nested structure:");
console.log(studentDetails);
Original nested structure:
[
{
studentId: 101,
studentName: 'John',
subjectDetails: { subjectName: 'JavaScript' }
},
{
studentId: 102,
studentName: 'David',
subjectDetails: { subjectName: 'MongoDB' }
}
]
Solution: Using map() to Un-nest
The map() method allows you to transform each object by extracting nested properties and creating a new flattened structure:
const studentDetails = [
{
"studentId": 101,
"studentName": "John",
"subjectDetails": {
"subjectName": "JavaScript"
}
},
{
"studentId": 102,
"studentName": "David",
"subjectDetails": {
"subjectName": "MongoDB"
}
}
];
const output = studentDetails.map(obj => ({
studentId: obj.studentId,
studentName: obj.studentName,
subjectName: obj.subjectDetails.subjectName
}));
console.log("Un-nested structure:");
console.log(output);
Un-nested structure:
[
{ studentId: 101, studentName: 'John', subjectName: 'JavaScript' },
{ studentId: 102, studentName: 'David', subjectName: 'MongoDB' }
]
How It Works
The map() method:
- Iterates through each object in the array
- Uses destructuring to extract nested properties
- Returns a new object with a flattened structure
- Maintains the original array length while transforming each element
Alternative: Using Spread Operator
You can also use the spread operator for more complex un-nesting scenarios:
const studentDetails = [
{
"studentId": 101,
"studentName": "John",
"subjectDetails": {
"subjectName": "JavaScript",
"grade": "A"
}
}
];
const output = studentDetails.map(obj => ({
...obj,
...obj.subjectDetails,
subjectDetails: undefined
})).map(({subjectDetails, ...rest}) => rest);
console.log(output);
[
{
studentId: 101,
studentName: 'John',
subjectName: 'JavaScript',
grade: 'A'
}
]
Conclusion
The map() method is the most effective way to un-nest arrays of objects in JavaScript. It allows you to extract nested properties and create a flattened structure while preserving data integrity.
