Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through json array jquery

Tags:

json

jquery

loops

I'm trying to loop through this to get the 'name' values. This is what I currently have, but it doesn't seem to be working, tried a few others from what was posted here but nothing seemed to work.

    $.get("/get_names", {campaign_id: $('select[name="id"]').val()},                  function(data){                     $.each(data, function(i, item) {                         alert(item);                     });                 }    ); 

Json being returned:

   [            {               "name":"age"            },            {               "name":"asdf"            },            {               "name":"drivername"            },            {               "name":"drivers"            },            {               "name":"firstname"            },            {               "name":"gender"            },            {               "name":"lastname"            },            {               "name":"make"            },            {               "name":"model"            },            {               "name":"vehicles"            },            {               "name":"year"            }         ] 

I've tried using:

item.name item[i].name 

Any suggestions?

Thank you!

like image 393
dzm Avatar asked Oct 14 '11 17:10

dzm


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 loop through object in jQuery?

The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.


2 Answers

You have to parse the string as JSON (data[0] == "[" is an indication that data is actually a string, not an object):

data = $.parseJSON(data); $.each(data, function(i, item) {     alert(item); }); 
like image 82
Rob W Avatar answered Oct 07 '22 06:10

Rob W


you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

like image 30
Kevin B Avatar answered Oct 07 '22 04:10

Kevin B