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);
Answer from Deathspike on Stack Overflow
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.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-json-object-in-javascript
How to Iterate JSON Object in JavaScript? - GeeksforGeeks
July 23, 2025 - Inside the loop, we can access ... of the keys from a JSON object. This array of keys can then be iterated over using the forEach method....
Discussions

How to loop through an array with JSON objects
const arr = [ {title: " some title", id: "some id"}, {title: " some title2", id: "some id2"} ] console.log( "For loop") for( let i = 0; i< arr.length; i++) { console.log(arr[i].id) } console.log( "Use of") for ( let item of arr) { console.log( item.id) } console.log( "Use forEach - recommended") arr.forEach( (item) => console.log( item.id)); console.log( "Use forEach plus destructuring - recommended") arr.forEach( ({id}) => console.log( id)); console.log( "Use map to transform array, then log array") const result = arr.map( ({id}) => id) ; console.log( result) Output: For loop some id some id2 Use of some id some id2 Use forEach - recommended some id some id2 Use forEach plus destructuring - recommended some id some id2 Use map to transform array, then log array [ 'some id', 'some id2' ] P.S. If you are using var to declare a variable, you probably shouldn't be. Use const and let where possible. More on reddit.com
🌐 r/learnjavascript
9
4
December 30, 2022
javascript - How do I iterate over a JSON structure? - Stack Overflow
It should be "jQuery or pure JavaScript". ... "How do I iterate over a JSON structure?" You don't. You parse it, whereupon you don't have JSON anymore, and you loop through the resulting array. T.J. Crowder – T.J. Crowder · 2017-05-09 13:24:26 +00:00 Commented May 9, 2017 at 13:24 ... Vote to reopen because while Array's and Objects ... More on stackoverflow.com
🌐 stackoverflow.com
Loop through json
Hi, I get a json object from a webhook. I would look to loop though all blocks (see the image below), nb. of block could vary from 0 to10. I guess I should use SplitInBatches but despite having seen some example I don’t know how to do it… Is that node is the right to use or there something ... More on community.n8n.io
🌐 community.n8n.io
1
0
May 19, 2023
help iterating through json objects

Depends how many nested levels there are. If it's as the example shows, then a simple loop will get you what you want. If you need the access the key of the object and the objects nested in the arrays use for in. If not, you can use for of.

for (const key in obj) {
    // key here would be "asdf" in your example
    for (const index in obj[key]) {
        // index here would be the index of the array of "asdf"
        for (const nestedObjKey in obj[key][index]) {
            // nestedObjKey would be "date", etc. in your example
            // obj[key][index][nestedObjKey] would be "2020-1-22", etc. in your example
        }
    }
}
More on reddit.com
🌐 r/learnjavascript
2
1
March 31, 2020
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Possible to iterate through a JSON object and return values of each property? - JavaScript - The freeCodeCamp Forum
July 3, 2017 - Hey all, I’m trying to add a shopping list to my Recipe box project as an extra personalization, and when researching on how to do this, one camper recommended that in order for me to render my Shopping list in a different target, I make a stateful component, and update the state as I add ...
🌐
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"

🌐
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 an example; you’ve got an object containing some properties and you need to look up each property and the value that it carries. 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 JavaScript Object Notation.
🌐
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
🌐
Futurestud.io
futurestud.io › tutorials › iterate-through-an-objects-keys-and-values-in-javascript-or-node-js
Iterate Through an Object’s Keys and Values in JavaScript or Node.js
March 3, 2022 - This tutorial walks you through each of these loops to iterate through an object’s keys and values. ... The most recent addition to JavaScript is Object.entries. This method returns an array containing tuples. Each tuple is an array with two items, the key, and value. The tuple’s key is the first item and the value comes second. Here’s an example of the output of the Object.entries method: const tutorials = { nodejs: 123, android: 87, java: 14, json: 7 } const entries = Object.entries(tutorials) // [ // ['nodejs', 123], // ['android', 87], // ['java', 14], // ['json', 7] // ]
🌐
ZetCode
zetcode.com › javascript › jsonforeach
JavaScript JSON forEach - Iterating Over JSON Arrays
This code defines a JSON array of users, where each user has a name and a nested array of tasks. Each task has a title and a completion status. We use forEach to iterate over the users and their tasks, printing the user's name and each task's title and completion status to the console.
🌐
TutorialsPoint
tutorialspoint.com › how-to-iterate-json-array-javascript
How to iterate json array - JavaScript?
Choose the iteration method based on your needs: use traditional for loops when you need index control, for...of for clean modern syntax, or forEach() for functional programming approaches. Each method effectively handles JSON array iteration in different scenarios.
🌐
Jsdiaries
jsdiaries.com › how to loop through json in javascript
How to loop through JSON in JavaScript | The JavaScript Diaries
March 23, 2020 - Typically, this is when you have a JSON object containing various information from an endpoint. ... We cycle through each property and output the value by referencing the current prop in our object. And if we want the names of the property keys we can iterate through them like so:
🌐
Crunchify
crunchify.com › json tutorials › how to iterate through jsonarray in javascript
How to Iterate through JSONArray in JavaScript • Crunchify
April 7, 2023 - During each iteration, you can access the properties of each JSON object using the dot notation or bracket notation. The data can be displayed or manipulated in various ways, such as adding it to a table or performing calculations on it. Iterating through a JSONArray in JavaScript is a fundamental ...
🌐
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 ...
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
Iterate over JSON with Root Node in JavaScript | Pluralsight
Root nodes in JSON give you a better understanding of the response object. In cases where JSON responses contain similar data types, you can combine them into one and iterate through all of them together, but it largely depends on how your database is set up. The generalized approach is to access them through the root node individually and iterate over only those properties that can be iterated over (such as arrays and strings), as shown in this guide.
🌐
DEV Community
dev.to › fariharajput › speedy-tip-how-to-loop-through-a-json-response-in-javascript-6a1
Speedy Tip: How to Loop Through a JSON Response in JavaScript - DEV Community
May 6, 2021 - Use Object.entries, Object.values or Object.entries An alternative approach to the above is to use one of Object.keys(), Object.values() or Object.entries(). These will return an array which we can then iterate over.
🌐
Codemia
codemia.io › knowledge-hub › path › how_to_iterate_over_a_jsonobject
How to iterate over a JSONObject?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
🌐
Logfetch
logfetch.com › js-iterate-json
How to Iterate Through JSON Objects in JavaScript - LogFetch
May 6, 2020 - It seems that the for … in method is the fastest (and, in my opinion, the cleanest) method for iterating through a JSON object. Keep in mind that object properties are not stored in any order, so when we iterate over an object, we can’t guarantee any order in which they will appear. How to Validate a UUID with Regular Expressions in JavaScript