How do I iterate over a JSON structure?

JavascriptJsonLoops

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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));
});

Solution 3 - Javascript

Use for...of:

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

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

Result:

Susita
BMW

Solution 4 - Javascript

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]);
}

Solution 5 - Javascript

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;
});

Solution 6 - Javascript

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

Solution 7 - Javascript

mootools example:

var ret = JSON.decode(jsonstr);

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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);
});

Solution 11 - Javascript

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

Solution 12 - Javascript

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>

Solution 13 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlueras BogdanView Question on Stackoverflow
Solution 1 - JavascriptYour Friend KenView Answer on Stackoverflow
Solution 2 - JavascriptMarquis WangView Answer on Stackoverflow
Solution 3 - JavascriptAlikElzin-kilakaView Answer on Stackoverflow
Solution 4 - JavascriptabdulbasitView Answer on Stackoverflow
Solution 5 - JavascriptSwapnil GodambeView Answer on Stackoverflow
Solution 6 - JavascriptGerrit BrinkView Answer on Stackoverflow
Solution 7 - JavascriptJasonView Answer on Stackoverflow
Solution 8 - JavascriptMat RyerView Answer on Stackoverflow
Solution 9 - JavascriptFatima ZohraView Answer on Stackoverflow
Solution 10 - JavascriptFabien SnauwaertView Answer on Stackoverflow
Solution 11 - JavascriptkartoView Answer on Stackoverflow
Solution 12 - JavascriptVaughn GavinView Answer on Stackoverflow
Solution 13 - JavascriptGhislain FournyView Answer on Stackoverflow