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' }
]

Updated on: 07-Sep-2020

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements