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 - This tutorial will guide you on how to loop the array of JSON objects in JavaScript. We’ll explain the types of loops and how to use them.
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 through JSON array? - Stack Overflow
Well, all I can see there is that you have two JSON objects, seperated by a comma. If both of them were inside an array ([...]) it would make more sense. And, if they ARE inside of an array, then you would just be using the standard "for var i = 0..." type of loop. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Looping through nested json object - Stack Overflow
I have a badly designed JSON object which unfortunately I cannot change at this moment which contains a number of objects. Here is an example of what I am working with: var land = [ {"name":"c... More on stackoverflow.com
🌐 stackoverflow.com
August 26, 2016
🌐
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...
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 - 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.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-json-object-in-javascript
How to Iterate JSON Object in JavaScript? - GeeksforGeeks
July 23, 2025 - The for...of loop can be used with Object.entries() to iterate over the [key, value] pairs of a JSON object. The Object.entries(obj) method returns an array of [key, value] pairs from the object.
🌐
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 - By following the steps outlined in this tutorial, you can create a function that will loop through any JSON object and access all of its nested data structures. I hope you enjoyed this tutorial. Happy Coding! ... Lead Front-End JavaScript Engineer, React, Node.js, Accessibility Advocate https://www.alaneicker.com/
🌐
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. Here, nodes is an array of node. jsonloop.findNodes(obj, {'role': /engineer/i, 'birth': {'>=': 1985, '<': 1990}}, function(err, nodes) { nodes.forEach(function(node) { console.dir(node); }); });
Starred by 19 users
Forked by 6 users
Languages   JavaScript 56.8% | HTML 43.2% | JavaScript 56.8% | HTML 43.2%
🌐
Medium
medium.com › @beckerjustin3537 › javascript-using-array-iteration-methods-on-a-json-file-with-nested-objects-2c66b25df91e
JavaScript: Using Array Iteration Methods on a JSON file with Nested Objects | by Justin Becker | Medium
May 16, 2023 - These methods allow you to iterate through arrays, transform elements in arrays, filter data, find specific data, and perform complex calculations within your code. By understanding array iterations you will be able to write more readable code, enhance your ability to work with JSON files that contain nested objects, and create powerful JavaScript ...
🌐
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 - A for…in loop iterates over all enumerable properties of an object: const res = JSON.parse(xhr.responseText); for (const key in res){ if(obj.hasOwnProperty(key)){ console.log(`${key} : ${res[key]}`) } } // id : H6Elb2LBdxc // joke : What's ...
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.
🌐
Reddit
reddit.com › r/learnjavascript › how to loop through an array with json objects
r/learnjavascript on Reddit: How to loop through an array with JSON objects
December 30, 2022 -

Hi all,

Im really struggling with this problem today. So basically, I have an array in the format

arr = [{title: " some title", id: "some id"}, {title: " some title2", id: "some id2"}] and all im trying to do is loop through each item in the array and get the value of the ids.

Here is what ive tried:

for( var i = 0; i< arr.length; i++){

console.log(arr[i].id)

}

It keeps showing up as undefined, please can anyone assist me? I would like the result to be "some id"

🌐
ZetCode
zetcode.com › javascript › jsonforeach
JavaScript JSON forEach - Iterating Over JSON Arrays
Master how to loop through JSON arrays in JavaScript using the forEach method. This tutorial includes practical examples, syntax, and step-by-step guidance.