Fawaz Qamar
Fawaz Qamar

Reputation: 71

jQuery.each - How to iterate over JSON objects element?

i am very new to play with JSON. I need to iterate over JSON response coming from AJAX, actually, i am fetching checkboxe values from db table in the form on 2,3,7,9,3. Now i am stuck with iteration on each number.

If you run following code in FF console area you will notice it is looping against each numeric NOT THE VALUE.

Please guide me.

var srv = {"services":"26,29"};

jQuery.each( srv.services, function(i, v) {
    console.log( v );
});

Any help would be appreciated. THanks :)

Upvotes: 1

Views: 2366

Answers (4)

Andy E
Andy E

Reputation: 344803

srv.services is a string of comma separated values, so $.each() won't work correctly. You can split() it into an array, though:

var srv = {"services":"26,29"};

jQuery.each(srv.services.split(","), function(i, v) {
    console.log( v );
});

Working demo: http://jsfiddle.net/AndyE/veP4p/

You could also have your JSON service return an array instead of a string, e.g. {"services":[26, 29]}. This would be done for you automatically at the server if you're using proper JSON-compliant methods to encode and if the data is an array.

Upvotes: 7

Robert Koritnik
Robert Koritnik

Reputation: 105091

You have to create an array first

var srv = {"services":"26,29".split(",")};

jQuery.each( srv.services, function(i, v) {
    console.log( v );
});

Upvotes: 0

Pavel Morshenyuk
Pavel Morshenyuk

Reputation: 11481

it is not valid json array, your json data should be something like this:

var srv = {"services": ["26", "29"]};

..or of-cause you could split your string data using js split function:

jQuery.each(srv.services.split(","), function(i, v) {
    console.log( v );
});

Upvotes: 1

jensgram
jensgram

Reputation: 31518

Not sure this is an answer to your problem but given the declaration from above, try splitting on , before iterating:

var srv = {"services":"26,29"};

jQuery.each( srv.services.split(','), function(i, v) {
    console.log( v );
});

(Demo)

Upvotes: 0

Related Questions