How to use JavaScript map() method to access nested objects?


Let’s say the following is our nested objects −

var details = [
   {
      id:"101",
      firstName:"John",
      lastName:"Smith",
      age:25,
      countryName:"US",
      subjectDetails: {
         subjectId:"Java-101",
         subjectName:"Introduction to Java"
      },
   },
   {
      "uniqueId": "details_10001"
   }
]

Use map() along with typeOf to access nested objects. Following is the code −

Example

var details = [
   {
      id:"101",
      firstName:"John",
      lastName:"Smith",
      age:25,
      countryName:"US",
      subjectDetails: {
         subjectId:"Java-101",
         subjectName:"Introduction to Java"
      },
   },
   {
      "uniqueId": "details_10001"
   }
]
details.map((nestedObject)=>{
   if (typeof nestedObject.subjectDetails != 'undefined')
   console.log("The subject Name="+nestedObject.subjectDetails.subjectName);
})

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo119.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo119.js
The subject Name=Introduction to Java

Updated on: 09-Sep-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements