Skip to content

Loop through nested json object JavaScript

  • by

You can use a combination of for...in loops and recursion to Loop through nested json objects in JavaScript. Steps to do recursively:-

  1. You build one function which takes an object as an argument and iterates through its entries. It checks the value of each entry and handles it;
  2. if the value is an array – it calls an array iteration function which also handles the value in the same way
  3. if it is an object – it just calls itself

Loop through nested json object JavaScript examples

Simple example code.

<!DOCTYPE html>
<html>

<body>
  <script >
    const data = {
      "name": "John",
      "age": 30,
      "address": {
        "city": "New York",
        "state": "NY",
        "country": "USA"
      }
    };

    function loopThroughObject(obj) {
      for (let key in obj) {
        if (typeof obj[key] === 'object') {
          loopThroughObject(obj[key]);
        } else {
          console.log(`${key}: ${obj[key]}`);
        }
      }
    }

    loopThroughObject(data);


  </script>
</body>
</html>

Output:

Loop through nested json object JavaScript

Iterate through nested JSON Object Array

const data = {
  "name": "John",
  "age": 30,
  "addresses": [
    {
      "city": "New York",
      "state": "NY",
      "country": "USA"
    },
    {
      "city": "Los Angeles",
      "state": "CA",
      "country": "USA"
    }
  ]
};

function loopThroughObjectArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    const obj = arr[i];
    for (let key in obj) {
      if (typeof obj[key] === 'object') {
        loopThroughObjectArray(obj[key]);
      } else {
        console.log(`${key}: ${obj[key]}`);
      }
    }
  }
}

loopThroughObjectArray(data.addresses);

Use JavaScript to loop to get the first city name, and then loop to get its places, then get the second city and its places, and so on.

var City = {
  "City1": [{
    "name": "Place 1"
  }, {
    "name": "Place 2"
  }, {
    "name": "Place 3"
  }],
  "City2": [{
    "name": "My Place 1"
  }, {
    "name": "My Place 2"
  }, {
    "name": "My Place 3"
  }],
  "City3": [{
    "name": "My Place 1"
  }, {
    "name": "My Place 2"
  }, {
    "name": "My Place 3"
  }]
};

Object.keys(City).forEach(function(value, key) {
  console.log(value);
  City[value].forEach(function(v, k) {
    console.log(v.name)
  })
});

Output:

Iterate through nested json object array

Do comment if you have any doubts or suggestions on this JS JSON object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *