
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Key Value from a Nested Object in JavaScript
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
Advertisements