Extract key value from a nested object in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let us first create a nested object −

var details = {
   "teacherDetails":
   {
      "teacherName": ["John", "David"]
   },
   "subjectDetails":
   {
      "subjectName": ["MongoDB", "Java"]
   }
}

Let us now extract the keys. Following is the code −

Example

var details = {
   "teacherDetails":
   {
      "teacherName": ["John", "David"]
   },
   "subjectDetails":
   {
      "subjectName": ["MongoDB", "Java"]
   }
}
var objectName, nestedObject;
var name = "Java";
for(var key in details){
   for(var secondKey in details[key]){
      if(details[key][secondKey].includes(name)){
         objectName = key;
         nestedObject = secondKey;
      }
   }
}
console.log(objectName + ', ' + nestedObject);

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

node fileName.js.

Here, my file name is demo96.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo96.js
subjectDetails, subjectName
raja
Published on 07-Sep-2020 08:35:12
Advertisements