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
Selected Reading
Un-nesting array of object in JavaScript?
To un-nest array of objects, use the concept of map(). Let’s say the following are our array of objects −
const studentDetails = [
{
"studentId": 101,
"studentName": "John",
"subjectDetails": {
"subjectName": "JavaScript"
}
},
{
"studentId": 102,
"studentName": "David",
"subjectDetails": {
"subjectName": "MongoDB"
}
}
];
We need to un-nest the subjectName and display the result. Following is the code −
Example
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(output);
To run the above program, you need to use the following command −
node fileName.js.
Output
Here, my file name is demo92.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo92.js
[
{ studentId: 101, studentName: 'John', subjectName: 'JavaScript' },
{ studentId: 102, studentName: 'David', subjectName: 'MongoDB' }
] Advertisements
