Easy JavaScript - find value in nested JSON
Use a recursive function to find a value in a nested JSON object
by Nazmus Nasir
HTML
<!-- Easy JavaScript # 57 - Find value in nested JSON -->
<p>
Welcome to the 57th Easy JavaScript tutorial, part of <a href="https://www.easyprogramming.net">EasyProgramming.net</a>. Learn how you can find a value in a nested JSON object with a recursive method.
</p>
<p>
If you have this array of objects, how can you extract just the name and city?
</p>
<pre>
[
{
"name": "Nazmus",
"job": "Software Engineer",
"location": {
"city": "Boston",
"state": "Massachusetts",
}
},
{
"name": "Bill",
"job": "CEO",
"city": "Seattle",
"state": "Washington"
},
{
"name": "Bob",
"job": "Engineer",
"location": {
"addres": {
"state": "New York",
"city": "New York City",
"zip": "11323"
}
}
},
{
"name": "Chris",
"job": "Project Manager",
"address": {
"location": {
"quadrant": {
"block": 1,
"state": "Texas",
"city": "Austin"
}
}
}
}
]
</pre>
JavaScript
let data = [
{
"name": "Nazmus",
"job": "Software Engineer",
"location": {
"city": "Boston",
"state": "Massachusetts"
}
},
{
"name": "Bill",
"job": "CEO",
"city": "Seattle",
"state": "Washington"
},
{
"name": "Bob",
"job": "Engineer",
"location": {
"addres": {
"state": "New York",
"city": "New York City",
"zip": "11323"
}
}
},
{
"name": "Chris",
"job": "Project Manager",
"address": {
"location": {
"quadrant": {
"block": 1,
"state": "Texas",
"city": "Austin"
}
}
}
}
]
data.filter( item => {
iterateObject(item);
});
function iterateObject(obj) {
for(prop in obj) {
if(typeof(obj[prop]) == "object"){
iterateObject(obj[prop]);
} else {
if(prop == "name" || prop == "city") {
console.log(prop.toUpperCase() + ': ', obj[prop]);
}
}
}
}