Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop through JSON array in jQuery?

Tags:

json

jquery

loops

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..

like image 311
Niket Malik Avatar asked Dec 25 '13 11:12

Niket Malik


People also ask

How to loop through array in jQuery?

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.

How to loop JSON object in jQuery?

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.

How to iterate Over JSON object in JS?

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.


1 Answers

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); });  
like image 99
Dell Avatar answered Sep 22 '22 02:09

Dell