Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following JSON structure:

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

how to iterate over it using jquery or javascript?

share|improve this question

8 Answers

up vote 131 down vote accepted

Taken from jQuery docs (http://docs.jquery.com/Utilities/jQuery.each):

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));
});
share|improve this answer
61  
This is a very confusing syntax. Can you please explain it? Can you also provide the output? – kilaka Jun 23 '11 at 17:10
The answer should have been given in JavaScript, not JQuery. – Wayne Hartman May 31 at 3:10
Whoa... I use the same combination on my luggage. – oscilatingcretin May 31 at 18:57
 var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];

    for(var i=0;i<arr.length;i++){
        var obj = arr[i];
        for(var key in obj){
            var attrName = key;
            var attrValue = obj[key];
        }
    }

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

share|improve this answer
I love jQuery, but when it's not available, this is it! – Fronker Dec 6 '11 at 9:47
14  
+1 for raw JS!! – cvsguimaraes Nov 20 '12 at 18:33
1  
@cvsguimaraes We need a moderation tool for flagging JQuery answers given for JS questions. Sheesh. – Wayne Hartman May 31 at 3:12

Use foreach:

<html>
<body>
<script type="text/javascript">
var mycars = [{name:'Susita'}, {name:'BMW'}];
for (i in mycars)
{
  document.write(mycars[i].name + "<br />");
}
</script>
</body>
</html>

Will result in:

Susita
BMW
share|improve this answer
1  
The Susita is a culture dependent variable, right? :-) – GilShalit Dec 20 '10 at 12:26
1  
Right, a top level variable, like BMW ;-) – kilaka Jan 13 '11 at 9:45
This is a regular array, not JSON. – jonasespelita Oct 7 '11 at 7:13
1  
Edited to contain json objects – kilaka Oct 9 '11 at 10:03

This is your 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;
});
share|improve this answer

mootools example:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});
share|improve this answer

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

share|improve this answer

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

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

You can run it on http://www.zorba-xquery.com/html/demo#AwsGMHmzDgRpkFpv8qdvMjWLvvE=

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.