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. Answer from girl-InTheSwing on reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-json-object-in-javascript
How to Iterate JSON Object in JavaScript? - GeeksforGeeks
July 23, 2025 - To access both the keys and values of a JSON object, Object.entries() can be used. This method returns an array of [key, value] pairs from the object. The forEach method can then be applied to iterate through the array of entries.
🌐
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"

Discussions

iterating through object - javascript
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
java - How to iterate over a JSONObject? - Stack Overflow
Be careful everyone, jObject.keys() returns the iterator with reverse index order. 2013-08-31T17:36:12.997Z+00:00 ... @macio.Jun Nevertheless, the order doesn't matter in maps of properties: keys in JSONObject are unordered and your assertion was a simple reflection of a private implementation ;) 2013-10-01T13:55:03.283Z+00:00 ... Slight quibble: doesn't this lead to doing the key lookup twice? Maybe better to do 'Object ... More on stackoverflow.com
🌐 stackoverflow.com
How to iterate over a nested JSON object
Hello: I need to iterate over a nested field in a JSON like this: { "date":"2025-04-28", "object" : { "temp" : "24", "hum" : "49", "press" : "10" }, "error":"" } I’m using a Split Out node, configured to split by the “object” field, but the output looks like this: { "object" : "24" }, ... More on community.n8n.io
🌐 community.n8n.io
0
0
April 30, 2025
How do I iterate over a JSON structure?
"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 are ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Possible to iterate through a JSON object and return values of each property?
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 ...
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.

🌐
n8n
community.n8n.io › questions
How to iterate over a nested JSON object - Questions - n8n Community
April 30, 2025 - Hello: I need to iterate over a nested field in a JSON like this: { "date":"2025-04-28", "object" : { "temp" : "24", "hum" : "49", "press" : "10" }, "error":"" } I’m using a Split Out node, configured to split by the “object” field, but the output looks like this: { "object" : "24" }, ...
Find elsewhere
🌐
Baeldung
baeldung.com › home › json › iterating over an instance of org.json.jsonobject
Iterating Over an Instance of org.json.JSONObject | Baeldung
May 5, 2025 - For this, we can simply iterate through the keys using the keys() method: void handleJSONObject(JSONObject jsonObject) { jsonObject.keys().forEachRemaining(key -> { Object value = jsonObject.get(key); logger.info("Key: {0}\tValue: {1}", key, ...
🌐
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); }
🌐
ZetCode
zetcode.com › javascript › jsonforeach
JavaScript JSON forEach - Iterating Over JSON Arrays
The fetch function retrieves data as JSON array from the provided URL. With forEach, we go through the array. Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); });
🌐
Edureka Community
edureka.co › home › community › categories › java › iterate over a jsonobject
Iterate over a JSONObject | Edureka Community
June 27, 2018 - JSON library called JSONObject is used(I don't mind switching if I need to) We know how to iterate over ... http://url3.com//", "shares": 15 } }
🌐
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.
🌐
Blogger
javarevisited.blogspot.com › 2022 › 12 › how-to-iterate-over-jsonobject-in-java.html
How to iterate over JSONObject in Java to print all key values? Example Tutorial
May 21, 2023 - Well, yes, you can iterate over all JSON properties and also get the values from the JSONObject itself. In this article, I'll show you how you can print all keys and value from JSON message using JSONOjbect and Iterator. Once you parse your JSON String using JSONParser, you get a JSONObject, but its of no use if you want a POJO i.e. a plain old Java object.
Top answer
1 of 3
1

The names are a little confusing because of O and 0 ! But you are almost there, here is the fixed code which at least parses your sample json data correctly:

public class MyModel
{
    public Outputdata Outputdata { get; set; }
}

public class Outputdata
{
    public TASK_0 TASK_0 { get; set; }
    public string ERROR_O { get; set; }
}

public class TASK_0
{
    public List TASK_O_ITEM { get; set; }
}

public class TASK_O_ITEM
{
    public string CODE { get; set; }
    public string TASK_NAME { get; set; }
}

And the usage:

var responseBody = "the body from wherever you read";
var result = JsonConvert.DeserializeObject(responseBody);
foreach (var item in result?.Outputdata?.TASK_0?.TASK_O_ITEM)
    Console.WriteLine($"{item.CODE} - {item.TASK_NAME}");
2 of 3
0

Hi @Paul

My thoughts are:

  1. Declare classes and lists.
  2. Assign a value to the data.
  3. Generate JSON variables.
  4. Print it out

For demonstration purposes, I printed the JSON data as string data.

In order to keep the same format as JSON, I set an option.

var options = new JsonSerializerOptions { WriteIndented = true };

string jsonString = System.Text.Json.JsonSerializer.Serialize(outputdata, options);

Of course, you can also print it directly.

You can refer to the following code:

public class TASK_O
{
    public List TASK_O_ITEM { get; set; }
}
public class Outputdata
{
    public TASK_O TASK_O { get; set; }
    public string ERROR_O { get; set; }
}
public class Example
{
    public Outputdata Outputdata { get; set; }
}
public class TASK_O_ITEM
{
    public string CODE { get; set; }
    public string NAME { get; set; }
}
internal class Program
{
    static void Main(string[] args)
    {
        var task_o_item = new List {
            new TASK_O_ITEM
            {
                CODE = "123",
                NAME = "ABC"
            },
            new TASK_O_ITEM
            {
                CODE = "456",
                NAME = "DEF"
            },
            new TASK_O_ITEM
            {
                CODE = "789",
                NAME = "GHI"
            },
        };
        var task_O = new TASK_O
        {
            TASK_O_ITEM = task_o_item
        };
        var outputdata = new Outputdata
        {
            TASK_O = task_O,
            ERROR_O = null
        };
        var example = new Example
        {
           Outputdata=outputdata
        };
        var options = new JsonSerializerOptions { WriteIndented = true };
        string jsonString = JsonSerializer.Serialize(example, options);
        Console.WriteLine(jsonString);
        Console.Read();
    }
}

Result:

Best Regards

Qi You


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

🌐
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
🌐
Delft Stack
delftstack.com › home › howto › python › iterate through json python
How to Iterate Through JSON Object in Python | Delft Stack
February 2, 2024 - This method returns an iterable of key-value pairs, allowing us to directly unpack and print both the key and value within the loop. ... In this output, each line corresponds to a key-value pair in the JSON object.
🌐
Webkul
webkul.com › home › how to iterate through jsonobject in java and kotlin
How to Iterate through JSONObject in Java and Kotlin - Webkul Blog
January 16, 2026 - How to Iterate Through JSONObject in Java and Kotlin – Learn how to loop through a JSONObject and read key-value pairs in Java and Kotlin.
🌐
JanBask Training
janbasktraining.com › community › java › how-can-i-iterate-json-objects-in-java-programming-language
How can I iterate JSON objects in Java programming language? | JanBask Training Community
January 24, 2024 - ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonString); Iterator fieldNames = jsonNode.fieldNames(); While (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode value = jsonNode.get(fieldName); // Your logic here, for example: System.out.println(“Field: “ + fieldName + “, Value: “ + value); } } catch (Exception e) { e.printStackTrace(); } } }