618

I have the following JSON structure:

[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]

How do I iterate over it using JavaScript?

7
  • 1
    stackoverflow.com/questions/1050674/… Commented Jul 3, 2009 at 7:11
  • 7
    "jquery or javascript"? jquery is written in javascript! Commented Aug 28, 2014 at 12:09
  • 9
    It should be "jQuery or pure JavaScript". Commented Sep 17, 2015 at 11:16
  • 4
    "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. Commented May 9, 2017 at 13:24
  • 1
    Vote to reopen because while Array's and Objects are similar in javascript they have differences and this is one of them safely looping over an object's properties is a lot harder than an array in Javascript, and the answer linked to with the close covers explicitly only arrays, maybe needs pointing to a different question on the close but currently links to an answer that is not correct for this question Commented Oct 13, 2021 at 12:45

13 Answers 13

587

var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
    
for (var i = 0; i < arr.length; i++){
  document.write("<br><br>array index: " + i);
  var obj = arr[i];
  for (var key in obj){
    var value = obj[key];
    document.write("<br> - " + key + ": " + value);
  }
}

note: the for-in method is cool for simple objects. Not very smart to use with DOM object.

Sign up to request clarification or add additional context in comments.

8 Comments

Don't forget to check right inside your for key in obj loop that obj.hasOwnProperty(key) --- else one day you might find other keys working their way into obj that you don't want, if someone extends the prototype for example...
Hi can i just ask if i wanna use this to get a remote json array how do i do it? please give me some guidance!
@AlexanderSupertramp it is set using array literal notation with objects in object literal notation. In JavaScript arrays are essentially also objects. So I would still refer to the arr is set using JSON.
@musicformellons Refer to developer.mozilla.org/en/docs/Web/JavaScript/Reference/… for a modern approach (not supported by IE).
Never - never! - use a for...in-loop to enumerate over an array.
|
463

Taken from jQuery docs:

var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(arr, function() {
  $("#" + this).text("My id is " + this + ".");
  return (this != "four"); // will stop running to skip "five"
});

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});

6 Comments

This is a very confusing syntax. Can you please explain it? Can you also provide the output?
The answer should have been given in JavaScript, not JQuery.
@WayneHartman I sympathize with your point of view, but the original question does say "jquery or javascript." Seems like the error was in not having a jquery tag on the question.
Similarly, lodash offers _.forEach (alias _.each for underscore compatibility) to accomplish the same.
The OP asked for either jQuery or JavaScript, so the answer is suitable in my book.
|
129

Use for...of:

var mycars = [{name:'Susita'}, {name:'BMW'}];

for (var car of mycars) 
{
  document.write(car.name + "<br />");
}

Result:

Susita
BMW

13 Comments

The Susita is a culture dependent variable, right? :-)
Right, a top level variable, like BMW ;-)
This is a regular array, not JSON.
@SachinPrasad No, i is a property name.
Works on both arrays and jsons.
|
101

Please let me know if it is not easy:

var jsonObject = {
  name: 'Amit Kumar',
  Age: '27'
};

for (var prop in jsonObject) {
  alert("Key:" + prop);
  alert("Value:" + jsonObject[prop]);
}

2 Comments

Your jsonObject is not a real JSON object. It is a javascript object. That is why this works. However if anybody have a JSON object he can convert it to a JS object and then use your method. To convert a JSON object to JS object use jsObject = JSON.parse(jsonObject);
If you've acquired your data via jQuery.getJSON() then this works just fine.
39

If this is your dataArray:

var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];

then:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
         var ID = this.id;
         var CLASS = this.class;
});

1 Comment

Best answer using JQuery. I encode data from backend using AJAX so I did not use 'stringify' function. Code clear and beautiful !
21

Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];
}

RESULT: John Doe 25

Comments

18

mootools example:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});

Comments

14

Marquis Wang's may well be the best answer when using jQuery.

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.

Short and easy:

var results = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"} ];

results.forEach(function(item) {
    console.log(item);
});

1 Comment

Nice one-liner example. The thing that can be added on top of this is arrow function like- results.forEach((item) => console.log(item));
11

You can use a mini library like objx - http://objx.googlecode.com/

You can write code like this:

var data =  [ {"id":"10", "class": "child-of-9"},
              {"id":"11", "class": "child-of-10"}];

// alert all IDs
objx(data).each(function(item) { alert(item.id) });

// get all IDs into a new array
var ids = objx(data).collect("id").obj();

// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()

There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary

Comments

11

With nested objects, it can be retrieve as by recursive function:

function inside(events)
  {
    for (i in events) {
      if (typeof events[i] === 'object')
        inside(events[i]);
      else
      alert(events[i]);
    }
  }
  inside(events);

where as events is json object.

1 Comment

Great. Just to have it mentioned; if you read out the (i) variable, you can get the property names (for what it's worth)
9

this is a pure commented JavaScript example.

  <script language="JavaScript" type="text/javascript">
  function iterate_json(){
            // Create our XMLHttpRequest object
            var hr = new XMLHttpRequest();
            // Create some variables we need to send to our PHP file
            hr.open("GET", "json-note.php", true);//this is your php file containing json

            hr.setRequestHeader("Content-type", "application/json", true);
            // Access the onreadystatechange event for the XMLHttpRequest object
            hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                    var data = JSON.parse(hr.responseText);
                    var results = document.getElementById("myDiv");//myDiv is the div id
                    for (var obj in data){
                    results.innerHTML += data[obj].id+ "is"+data[obj].class + "<br/>";
                    }
                }
            }

            hr.send(null); 
        }
</script>
<script language="JavaScript" type="text/javascript">iterate_json();</script>// call function here

Comments

5

var jsonString = `{
    "schema": {
        "title": "User Feedback",
        "description": "so",
        "type": "object",
        "properties": {
            "name": {
                "type": "string"
            }
        }
    },
    "options": {
        "form": {
            "attributes": {},
            "buttons": {
                "submit": {
                    "title": "It",
                    "click": "function(){alert('hello');}"
                }
            }
        }
    }
}`;

var jsonData = JSON.parse(jsonString);

function Iterate(data)
{
    jQuery.each(data, function (index, value) {
        if (typeof value == 'object') {
            alert("Object " + index);
            Iterate(value);
        }
        else {
            alert(index + "   :   " + value);
        }
    });
}

Iterate(jsonData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

1 Comment

You should explain your code. An answer without explanation doesn't help much.
3

Another solution to navigate through the JSON document is JSONiq (implemented in the Zorba engine), where you can write something like this:

let $doc := [
  {"id":"10", "class": "child-of-9"},
  {"id":"11", "class": "child-of-10"}
]
for $entry in members($doc) (: binds $entry to each object in turn :)
return $entry.class         (: gets the value associated with "class" :)

You can run it on http://public.rumbledb.org:9090/public.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.