Search Nested JSON with Recursive Function

Published on: March 26, 2020

Welcome to the 57th Easy JavaScript Tutorial!  I'm still working on new Raspberry Pi tutorials but I didn't want to go too long without posting a tutorial so I decided to do a quick JavaScript tutorial. 

The objective of this tutorial is to learn how to recursively crawl through an array of nested JSON data. We want to extract small pieces of data from a larger JSON object. In the example below, let's say we want to extra name and city:

    "name": "Nazmus",
    "job": "Software Engineer",
    "location": {
      "city": "Boston",
      "state": "Massachusetts",
    "name": "Bill",
    "job": "CEO",
    "city": "Seattle",
    "state": "Washington"

If every JSON object of our array looked the same, then we wouldn't need a function, we could use our basic bracket or dot notation to get what we need like array[0] But as you'll notice, the data structure for both of these are different. This isn't something that will happen every day but if you need to create an app that shouldn't care about the data structure, a recursive function like below will do the trick. 

function iterateObject(obj) {
   for(prop in obj) {
  	if(typeof(obj[prop]) == "object"){
    } else {
    	if(prop == "name" || prop == "city") {
      	  // Do something with this data

Our method named iterateObject() takes one argument of object. The loop will iterate through each object property and determine whether it's of type object. If it is, it'll take the value of that value and pass it back to the iterateObject() method. And if it's not an object, keep going and do something with that code, whether do a calculation, make an ajax call, or just log it to the console. Pretty simple right?

For more info on the loop, check out my loop tutorial.

For the complete code, check out the JS fiddle in the following link or see the embedded version below:

If you have questions, feel free to ask! Remember to come back for more tutorials. 

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!