I have a PHP page from which I get response in JSON:
[{'com':'something'},{'com':'some other thing'}]
I want to loop it and append each to a div.
This is what I tried:
var obj = jQuery.parseJSON(response); $.each(obj.com, function(key,value) { alert(key+':'+value); }
This alerts as undefined
, and also response is the JSON array..
Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.
jQuery code snippet to loop through JSON data properties. You have an array of objects/maps so the outer loop loops through those. The inner loop loops through the properties on each object element.
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.
Your array has default keys(0,1) which store object {'com':'some thing'}
use:
var obj = jQuery.parseJSON(response); $.each(obj, function(key,value) { alert(value.com); });
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