You can do something like

for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

Answer from hvgotcodes on Stack Overflow
🌐
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

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
javascript - How do I iterate over a JSON structure? - Stack Overflow
Here is something quite similar in pure JavaScript, using JavaScript's forEach method. forEach takes a function as an argument. That function will then be called for each item in the array, with said item as the argument. More on stackoverflow.com
🌐 stackoverflow.com
JavaScript Json Array foreach? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
Loop through JSON array
I’m building an English test for a page on a friend’s site. There are 50 multiple choice questions, using radio buttons to select the answer. I want the answers to be emailed to him along with the person’s details so i’m using a PHP script. I can get the input text boxes values and ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
October 21, 2016
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-json-object-in-javascript
How to Iterate JSON Object in JavaScript? - GeeksforGeeks
July 23, 2025 - The forEach method can then be applied to iterate through the array of entries. Inside the loop, both the key and value of each property can be accessed directly. ... const obj = { "company": 'GeeksforGeeks', "contact": '+91-9876543210', "city": ...
🌐
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 method is used for looping through an array element. Here’s an example of this: {% code-block language="js" %} var names = ["jerry", "tom", "pluto", "micky", "mini"]; names.forEach(function1); function function1(currentValue, index) { console.log("Index in array is: "+index + " :: Value is: "+currentValue); } ‍{% code-block-end %}
Find elsewhere
🌐
CodePen
codepen.io › YannickFricke › pen › Vqzoob
JavaScript forEach example with JSON data
Minimize JavaScript Editor · Fold All · Unfold All · let html = ''; // JSON from json_encode($data) let json = [{"category_id":39,"chapters":[{"link":"http:\/\/google.de","chapter_name":"First chapter"}]},{"category_id":37,"chapters":[{"link":"http:\/\/google.de","chapter_name":"Second chapter"}]},{"category_id":42,"chapters":[{"link":"http:\/\/google.de","chapter_name":"Third chapter"}]}]; json.forEach(function(element) { let category_id = element.category_id; let chapters = element.chapters; console.log(category_id); chapters.forEach(function(chapter) { html += '<a href="'+chapter.link+'">&raquo;Chapter '+chapter.chapter_name+'</a>' console.log(chapter.link); console.log(chapter.chapter_name); }) html += '<br />' }) console.log(html); document.getElementById('test').innerHTML = html; !
🌐
Crunchify
crunchify.com › json tutorials › how to iterate through jsonarray in javascript
How to Iterate through JSONArray in JavaScript • Crunchify
April 7, 2023 - The JSONArray can be accessed using ... into a JavaScript object, you can use a loop such as a for loop, a forEach loop, or a for…in loop to iterate through each object in the array....
🌐
TutorialsPoint
tutorialspoint.com › how-to-iterate-json-array-javascript
How to iterate json array - JavaScript?
<!DOCTYPE html> <html> <body> <div ... = output; </script> </body> </html> The forEach() method is a functional approach that executes a callback function for each array element....
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Loop through JSON array - JavaScript - The freeCodeCamp Forum
October 21, 2016 - I’m building an English test for a page on a friend’s site. There are 50 multiple choice questions, using radio buttons to select the answer. I want the answers to be emailed to him along with the person’s details so i’m using a PHP script. I can get the input text boxes values and ...
🌐
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, "city":"New York"}, {"name":"Jane", "age":20, "city":"Chicago"} ]; let filteredResponse = response.filter(function(item) { return item.age > 25; }); console.log(filteredResponse); In this example, the filter() method is used to create a new array that includes only the items where the ‘age’ property is greater than 25. Sorting a JSON response in JavaScript can be done using the sort() method.
Top answer
1 of 5
10

Your data should already be a javascript array because you've specified the JSON type for the jQuery Ajax call so it should have already parsed the JSON into javascript. As such, you can just directly iterate it as the array:

success: function (data) {
    for (var i = 0; i < data.length; i++) {
        var checkBox = "<input type='checkbox' data-price='" + data[i].Price + "' name='" + data[i].Name + "' value='" + data[i].ID + "'/>" + data[i].Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    }
    $('#addModifiers').modal('show');
}

Or, if you want to use jQuery's .each() iterator instead of a for loop, you can do this:

success: function (data) {
    $.each(data, function(key, item) {
        var checkBox = "<input type='checkbox' data-price='" + item.Price + "' name='" + item.Name + "' value='" + item.ID + "'/>" + item.Name + "<br/>";
        $(checkBox).appendTo('#modifiersDiv');
    });
    $('#addModifiers').modal('show');
}
2 of 5
6

You shouldn't be using var objects = JSON.stringify(data); since the data is already a JSON object.

Use JSON.stringify to create a string from a object

Use JSON.parse is to create an object from a string

Example:

var data = [{id: 1, name:'personsName'}, {id: 2, name:'personsName2'}]
var string = JSON.stringify(data)
var json = JSON.parse(string)

You can loop trough the data and append by using:

data.forEach(function(key, index){
   $("#modifiersDiv")
      .append($("<input></input>")
      .attr("type", "checkbox")
      .attr("data-price",key.Price )
      .attr("name",key.Name )
      .attr("value",key.ID)
      .text(key.Name); 
}
🌐
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 = JSON.stringify(response.getBody()); var httpStatus = response.getStatusCode(); var parsed = JSON.parse(responseBody); for (i = 0; i < parsed.addresses.length; i++) { gs.print(parsed.addresses[i].address1); }
🌐
GitHub
gist.github.com › chancesmith › 8d21d966b69eff170fae7fa4e5cfb4f5
Foreach loop through JSON object array · GitHub
Foreach loop through JSON object array · Raw · json-object-array-foreach-loop.php · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
🌐
Stack Overflow
stackoverflow.com › questions › 66494448 › how-to-change-json-in-array-in-foreach-loop-js › 66494856
javascript - How to change json in array in forEach loop ? JS - Stack Overflow
And I loop through the array: data.points.forEach((formData: IAddress) => { control.push(this.initiateForm(formData)); }); The obtained result is: { location: { latitude: 0, longitude: 0 }, name: "Point1", pointId: 1 } The desired result is: { latitude: 0, longitude: 0 name: "Point1", pointId: 1 } Just remove location JSON as if to eject longitude and latitude from the location. javascript ·