ObjectValues = function(v, k){
  if (typeof v == "object") {
    for (var kp in v) {
      if (Object.hasOwnProperty.call(v, kp)) {
        ObjectValues(v[kp], k != undefined ? k + "." + kp : kp);
      }
    }
  } else {
    console.log(k + ":" + v);
  }
};

should work even for JSON values that are not objects. It will work for

ObjectValues(JSON.parse("0"));

which would not be handled by the original and it will not iterate over characters in a top-level string if you do ObjectValues("http://...").

Answer from Mike Samuel on Stack Overflow
🌐
Microverse
microverse.org › home › blog › how to loop through the array of json objects in javascript
How to Loop Through the Array of JSON Objects in JavaScript
September 29, 2022 - Here’s how you would use the For In Loop to do so: {% code-block language="js" %} var person = { fname: "Nick", lname: "Jonas", age: 26 }; for (let x in person) { console.log(x + ": "+ person[x]) } ‍{% code-block-end %} JSON stands for ...
🌐
Quora
quora.com › How-do-you-loop-through-a-complex-JSON-tree-of-objects-and-arrays-in-JavaScript
How to loop through a complex JSON tree of objects and arrays in JavaScript - Quora
Answer (1 of 11): The clean answer is that you know, precisely, the structure of that JSON before you begin to read it. That allows you to know where the nested objects/keys are and where the arrays are to loop over them, etc. The dirty answer is that you can “discover” the nature of the structu...
Discussions

javascript - Iterate through nested json object array - Stack Overflow
So i need a proper looping structure in javascript that can be generic to handle it. It would be best if the loop stores product name in one var and it's version in another var as there are some checking i need to on product name. If the json structure is wrong or a better json structure can ... More on stackoverflow.com
🌐 stackoverflow.com
Loop through a nested JSON object
I’m looking for a solution to loop through a nested JSON object in pure JS. Indeed I’d like to console.log every item and each of its properties. Answer You are accessing an object’s value using its key in json_object[item] so just keep drilling down into the object. More on javascript.tutorialink.com
🌐 javascript.tutorialink.com
1
javascript - Loop thorough Json Object - JS - Stack Overflow
I am receiving a response in json form like below. How do i loop through to display the user of person1 and person2? I keep getting undefined in my console. What am i not doing right? data { "pe... More on stackoverflow.com
🌐 stackoverflow.com
javascript - iterating through object - Stack Overflow
I'm having a really hard time trying to find a way to iterate through this object in the way that I'd like. I'm using only Javascript here. First, here's the object { "dialog": { " More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 4
21

Since myJSONObject.abc contains a list of products it would make more sense to define the property abc as an array. Like this:

var myJSONObject = 
{
"abc":
    [
        [
            {"prod_ver" : "prod 1 ver 1"},
            {"prod_ver" : "prod 1 ver 2"},
        ],
        [
            {"prod_ver" : "prod 2 ver 1"},
            {"prod_ver" : "prod 2 ver 2"},
        ],
        [
            {"prod_ver" : "prod 3 ver 1"},
            {"prod_ver" : "prod 3 ver 2"},
        ]
    ]
};

Then you can iterate over the products and their versions using normal loops:

for(var i = 0; i < myJSONObject.abc.length; i++)
{
    var product = myJSONObject.abc[i];
    for(var j = 0; j < product.length; j++)
    {
        var version = product[j];
    }
}

You could take it slightly further and alter your JSON object's structure a bit to make it more easily understandable.

var catalog = 
{
    "products": [
        {
            "name": "prod 1",
            "versions": [
                "ver 1",
                "ver 2"
            ]
        },
        {
            "name": "prod 2",
            "versions": [
                "ver 1",
                "ver 2"
            ]
        }
    ]
};

for(var i = 0; i < catalog.products.length; i++)
{
    var product = catalog.products[i];
    var productName = product.name;
    for(var j = 0; j < product.versions.length; j++)
    {
        var version = product.versions[j];
    }
}
2 of 4
8

myJSONObject.abc is an object with keys like prod_1, prod_2, etc. You can loop through the keys of an object using for-in. So:

var productName;
var productVersionArray;

for (productName in myJSONObject.abc) {
    productVersionArray = myJSONObject.abc[productName];
}

Note that the order of the keys is not defined by the specification and will vary from JavaScript engine to JavaScript engine. If you want to do them in a particular order, you have to get an array of them, sort it in the order you want, and then loop through that array. (In an ES5-enabled environment, you can get an array of the keys of an object from Object.keys(yourObject). But you'd need a shim for older browsers.)

Within that loop, you can loop through the array using a standard for loop:

for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
    // Use `productVersionArray[versionIndex].prod_ver` here
}

Here's an example putting it all together:

(function() {

  var myJSONObject = 
    {
    "abc":
        {
            "prod_1": 
            [
                {"prod_ver" : "prod 1 ver 1"},
                {"prod_ver" : "prod 1 ver 2"}
            ],

            "prod_2": 
            [
                {"prod_ver" : "prod 2 ver 1"},
                {"prod_ver" : "prod 2 ver 2"}
            ],
            "prod_3": 
            [
                {"prod_ver" : "prod 3 ver 1"},
                {"prod_ver" : "prod 3 ver 2"}
            ]
        }
    };

  var productName;
  var productVersionArray;
  var versionIndex;

  for (productName in myJSONObject.abc) {
      productVersionArray = myJSONObject.abc[productName];
      display(productName + " has " + productVersionArray.length + " versions listed");
      for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
        display("* " + productVersionArray[versionIndex].prod_ver);
      }
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }

})();

Live Copy | Source

🌐
SitePoint
sitepoint.com › blog › javascript › how to loop through a json response in javascript
How to Loop Through a JSON Response in JavaScript — SitePoint
February 15, 2024 - Here’s an example: let response = { "name": "John", "age": 30, "address": { "street": "123 Main St", "city": "New York" } }; for (let key in response) { if (typeof response[key] === 'object') { for (let subKey in response[key]) { console.log(subKey + ": " + response[key][subKey]); } } else { console.log(key + ": " + response[key]); } } In this example, the outer loop iterates over each property in the ‘response’ object. If the property value is an object (i.e., a nested JSON object), the inner loop iterates over each property in the nested object. Converting a JavaScript object into a JSON string can be done using the JSON.stringify() method...
🌐
Medium
allaboutcode.medium.com › top-3-ways-to-loop-through-a-json-object-in-javascript-67ca21d33a24
Top 3 Ways to Loop Through a JSON Object in JavaScript | by Marika Lam | Medium
September 27, 2022 - Top 3 Ways to Loop Through a JSON Object in JavaScript 1. Use a for...in Loop A for…in loop iterates over all enumerable properties of an object: const res = JSON.parse(xhr.responseText); for …
🌐
ZetCode
zetcode.com › javascript › jsonforeach
JavaScript JSON forEach - Iterating Over JSON Arrays
const logBtn = document.getElementById('log'); logBtn.addEventListener('click', fetchData); async function fetchData() { const response = await fetch('http://localhost:3000/users/'); const data = await response.json(); data.forEach(obj => { Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); }); console.log('-------------------'); }); } The fetch function retrieves data as JSON array from the provided URL. With forEach, we go through the array.
Find elsewhere
🌐
GitHub
github.com › dabeng › JSON-Loop
GitHub - dabeng/JSON-Loop: JSON Loop is a super easy to use tool class helping you loop the deeply nested JSON object.
// find our uE engineer with her name jsonloop.findNodes(obj, {'name': 'xiaoxue'}, function(err, nodes) { nodes.forEach(function(node) { console.dir(node); }); }); // find young engineers in our team.
Starred by 19 users
Forked by 6 users
Languages   JavaScript 56.8% | HTML 43.2% | JavaScript 56.8% | HTML 43.2%
🌐
Medium
medium.com › @alaneicker › how-to-process-json-data-with-recursion-dc530dd3db09
Using Recursion in JavaScript to Traverse Nested Data Structures | by Alan Eicker | Medium
March 28, 2023 - Recursively looping through JSON ... recursively loop through JSON data using JavaScript. First, we need to create a JSON object that we can loop through....
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-json-object-in-javascript
How to Iterate JSON Object in JavaScript? - GeeksforGeeks
July 23, 2025 - Inside the forEach loop, each property value can be accessed using obj[key] ... const obj = { "company": 'GeeksforGeeks', "contact": '+91-9876543210', "city": 'Noida' }; Object.keys(obj).forEach(key => { console.log(`${key}: ${obj[key]}`); }); ... ...
Top answer
1 of 7
176

You use a for..in loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:

var obj = {a: 1, b: 2};
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    var val = obj[key];
    console.log(val);
  }
}

Or if you need recursion to walk through all the properties:

var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      var val = obj[key];
      console.log(val);
      walk(val);
    }
  }
}
walk(obj);
2 of 7
14

My problem was actually a problem of bad planning with the JSON object rather than an actual logic issue. What I ended up doing was organize the object as follows, per a suggestion from user2736012.

{
"dialog":
{
    "trunks":[
    {
        "trunk_id" : "1",
        "message": "This is just a JSON Test"
    },
    {
        "trunk_id" : "2",
        "message": "This is a test of a bit longer text. Hopefully this will at the very least create 3 lines and trigger us to go on to another box. So we can test multi-box functionality, too."
    }
    ]
}
}

At that point, I was able to do a fairly simple for loop based on the total number of objects.

var totalMessages = Object.keys(messages.dialog.trunks).length;

    for ( var i = 0; i < totalMessages; i++)
    {
        console.log("ID: " + messages.dialog.trunks[i].trunk_id + " Message " + messages.dialog.trunks[i].message);
    }

My method for getting totalMessages is not supported in all browsers, though. For my project, it actually doesn't matter, but beware of that if you choose to use something similar to this.

🌐
Stack Overflow
stackoverflow.com › questions › 26513119 › looping-over-complex-json-object
javascript - Looping over Complex JSON Object - Stack Overflow
I have created an application that accepts faxes in xml format and converts them to json objects so that I can take what I need from the fax which is the base64 string located in the "file contents" variable within the document.