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
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-json-object-in-javascript
How to Iterate JSON Object in JavaScript? - GeeksforGeeks
July 23, 2025 - In JavaScript, there are various ways to iterate over a JSON object, such as using the for...in loop, Object.keys(), Object.entries(), and for...of. Each method provides a simple and effective way to access the keys and values of a JSON object, ...
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.

Discussions

Possible to iterate through a JSON object and return values of each property?
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 ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
July 3, 2017
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
Iterate through json with javascript (forEach)
Platform information: Hardware: Raspberry Pi 4 with 4GB OS: Openhabian Java Runtime Environment:OpenJDK Runtime Environment Zulu11. openHAB version: 3.1.0.M5 I have a json-object which I like to evaluate with javascript. I wrote a script (or copied it from different places of the internet xD) ... More on community.openhab.org
🌐 community.openhab.org
1
0
June 26, 2021
How to loop through each item of a json array?
I have a .json file that I am using to have data for each level. I have an array in the .json file that i need to loop through the data for a level to generate it, except when i use this: for(i in leveldata){ loadLevel(levelData[i]); } it gives an error saying You can't iterate on a Dynamic ... More on community.haxe.org
🌐 community.haxe.org
5
0
April 27, 2021
🌐
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"

🌐
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 differ…
🌐
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 - Parsing JSON data from a server involves two steps: first, decoding the JSON string into a native JavaScript data structure (such as an array or object), and then iterating over this structure using JavaScript’s built-in methods like for...in, Object.entries, Object.values, or array methods such as forEach.
🌐
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.
Find elsewhere
🌐
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 ...
🌐
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.
🌐
ServiceNow Community
servicenow.com › community › developer-forum › iterate-through-array-in-json-object › m-p › 2198844
Iterate Through Array in JSON Object - ServiceNow Community
October 17, 2018 - var responseBody = response.getBody(); var httpStatus = response.getStatusCode(); var parser = new JSONParser(); var parsed = parser.parse(responseBody); for (i = 0; i < parsed.addresses.length; i++) { gs.print(parsed.addresses[i].address1); }
🌐
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...
🌐
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 blue and not very heavy?
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
Iterate over JSON with Root Node in JavaScript | Pluralsight
In this guide, you'll learn how ... iterate over them using JavaScript in React. ... A large portion of a frontend developer's work includes working with JSON responses when integrating backend APIs in an app. JSON responses are often complex and difficult to comprehend in one go. However, their complex structure is justified in terms of demystifying the data returned to the frontend. Thus, you may receive a JSON response with a root node indicating what the corresponding object is ...
Top answer
1 of 16
5192

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.

Here is the snippet:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

For-of with Object.keys() alternative:

var p = {
    0: "value1",
    "b": "value2",
    key: "value3"
};

for (var key of Object.keys(p)) {
    console.log(key + " -> " + p[key])
}

Notice the use of for-of instead of for-in, if not used it will return undefined on named properties, and Object.keys() ensures the use of only the object's own properties without the whole prototype-chain properties

Using the new Object.entries() method:

Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.

const p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (const [key, value] of Object.entries(p)) {
  console.log(`${key}: ${value}`);
}
2 of 16
1383

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

var obj = { first: "John", last: "Doe" };

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

ECMAScript 6 adds for...of:

for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

ECMAScript 8 adds Object.entries() which avoids having to look up each value in the original object:

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

You can combine for...of, destructuring, and Object.entries:

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value);
}

Both Object.keys() and Object.entries() iterate properties in the same order as a for...in loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.

🌐
Coderwall
coderwall.com › p › _kakfa › javascript-iterate-through-object-keys-and-values
JavaScript iterate through object keys and values (Example)
June 26, 2023 - I just wanted to keep this for reference how to quickly loop through an objects keys and values, if needed. I also included an implementation using jQuery .each · Note the limitations of using a for...in loop, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.