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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With