Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over a JSON structure? [duplicate]

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?

like image 462
Flueras Bogdan Avatar asked Jul 03 '09 07:07

Flueras Bogdan


People also ask

How do I iterate over a JSON structure?

Use Object.values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

How does JSON handle duplicate keys?

What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

Can you iterate through JSON?

We can use Object. entries() to convert a JSON array to an iterable array of keys and values. Object. entries(obj) will return an iterable multidimensional array.


1 Answers

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.

like image 83
Your Friend Ken Avatar answered Oct 19 '22 22:10

Your Friend Ken