604

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?

John
  • 1
  • 13
  • 98
  • 177
Flueras Bogdan
  • 9,187
  • 8
  • 32
  • 30
  • 1
    http://stackoverflow.com/questions/1050674/fastest-way-to-iterate-through-json-string-in-javascript – Max Jul 03 '09 at 07:11
  • 7
    "jquery or javascript"? jquery is written in javascript! – AlikElzin-kilaka Aug 28 '14 at 12:09
  • 9
    It should be "jQuery or pure JavaScript". – Rasshu Sep 17 '15 at 11:16
  • 3
    *"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](http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476). – T.J. Crowder May 09 '17 at 13:24
  • Made iterator IIFE https://github.com/eltomjan/ETEhomeTools/blob/master/HTM_HTA/JSON_Iterator_IIFE.js it has predefined (basic) DepthFirst & BreadthFirst next and ability to move inside JSON structure without recursion. – Jan Jul 09 '19 at 07:38
  • I think this question was rewritten to not mention jQuery, but according to other comments the original question did mention jQuery. This is confusing because the accepted answer does use jQuery, so it wouldn't apply to, say, a node.js situation. – paulkernfeld Jan 17 '21 at 19:57
  • 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 – Barkermn01 Oct 13 '21 at 12:45

13 Answers13

580

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.

Cristian
  • 654
  • 1
  • 13
  • 30
Your Friend Ken
  • 8,644
  • 3
  • 32
  • 41
  • 7
    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... – Funka Jan 17 '14 at 18:59
  • 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! – Hanzawa Naoki Aug 22 '14 at 02:44
  • @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. – Your Friend Ken Nov 19 '14 at 16:57
  • @devios So what would be a smart solution with a DOM object? – musicformellons Nov 23 '15 at 18:01
  • 1
    @musicformellons Refer to https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of for a modern approach (not supported by IE). – devios1 Nov 23 '15 at 19:55
  • Excellent. Doesn't require extra libraries. – bonhoffer Feb 07 '16 at 03:36
  • 1
    Never - never! - use a for...in-loop to enumerate over an array. – Stephan Weinhold Aug 11 '16 at 07:09
  • The "for in" occurs within each item of the array, on the nested object, not to iterate through the array itself. – wunth May 06 '18 at 18:53
459

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));
});
PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
Marquis Wang
  • 10,878
  • 5
  • 30
  • 25
  • 167
    This is a very confusing syntax. Can you please explain it? Can you also provide the output? – AlikElzin-kilaka Jun 23 '11 at 17:10
  • 152
    The answer should have been given in JavaScript, not JQuery. – Wayne Hartman May 31 '13 at 03:10
  • 24
    @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. – vlasits Jan 13 '14 at 18:39
  • Similarly, lodash offers [\_.forEach](https://lodash.com/docs#forEach) (alias [\_.each for underscore compatibility](http://underscorejs.org/#each)) to accomplish the same. – Ville Oct 25 '14 at 05:29
  • 5
    The OP asked for either jQuery or JavaScript, so the answer is suitable in my book. – KWallace Jul 03 '17 at 19:44
  • This is confusing because at some point it seems the question was rewritten to no longer mention jQuery ‍♂️ – paulkernfeld Jan 17 '21 at 19:58
122

Use for...of:

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

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

Result:

Susita
BMW
AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
94

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]);
}
abdulbasit
  • 1,856
  • 15
  • 17
  • 24
    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); – prageeth Oct 31 '14 at 04:48
  • 1
    If you've acquired your data via jQuery.getJSON() then this works just fine. – John Mee Apr 23 '15 at 05:37
40

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;
});
fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Swapnil Godambe
  • 2,054
  • 1
  • 24
  • 29
  • Best answer using JQuery. I encode data from backend using AJAX so I did not use 'stringify' function. Code clear and beautiful ! – danigonlinea Aug 17 '15 at 23:14
20

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

Gerrit Brink
  • 977
  • 3
  • 15
  • 26
18

mootools example:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});
Jason
  • 2,035
  • 11
  • 13
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

Mat Ryer
  • 3,797
  • 4
  • 26
  • 24
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.

Fatima Zohra
  • 2,929
  • 2
  • 17
  • 17
  • 1
    Great. Just to have it mentioned; if you read out the (i) variable, you can get the property names (for what it's worth) – netfed Jul 02 '13 at 08:27
11

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);
});
Cristian
  • 654
  • 1
  • 13
  • 30
Fabien Snauwaert
  • 4,995
  • 5
  • 52
  • 70
  • Nice one-liner example. The thing that can be added on top of this is arrow function like- ```results.forEach((item) => console.log(item));``` – quasar Nov 10 '21 at 07:13
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
karto
  • 3,538
  • 8
  • 43
  • 68
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>
Cristian
  • 654
  • 1
  • 13
  • 30
Vaughn Gavin
  • 69
  • 1
  • 3
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

Ghislain Fourny
  • 6,971
  • 1
  • 30
  • 37