Shaggie
Shaggie

Reputation: 1829

How to iterate through nested array of JSON in jQuery?

I have a data in json format getting from PHP script the data is coming in following format as follows:

[{
"type":"checkbox",
"grid-name":"Sports",
"values":["Cricket","Football"],
 "input":[{"Cricket":2},{"Football":1}]
},
{"type":"checkbox",
"grid-name":"Hobbies",
"values":["Playing Chess","Swimming"],
"input":[{"Playing Chess":1},{"Swimming":2}]
},
{"type":"radiobutton",
"grid-name":"Gender",
 "values":["Male","Female"],
"input":[{"Male":3},{"Female":0}]
},
{"type":"radiobutton",
"grid-name":"Citizen",
"values":["Indian","NRI"],
"input":[{"Indian":3},{"NRI":0}]
},
{"type":"number",
"grid-name":"Age",
"input":["24","23","23"]
},
 {"type":"select",
"grid-name":"City",
"values":["Satara","New york","Korea"],
"input":[{"Satara":1},{"New york":1},{"Korea":1}]
}]

i want to capture the values & input array. How to access through nested array?

Upvotes: 2

Views: 1899

Answers (2)

cn0047
cn0047

Reputation: 17091

jQuery:

$.each(yourObject, function( index, value ) {
    console.log(value.values);
    console.log(value.input);
});

Native js (but better don't use it, accordingly to this):

for (index in yourObject) {
    console.log(yourObject[index].values);
    console.log(yourObject[index].input);
}

Native js, another example:

for (var i = 0; i < yourObject.length; i++) {
    console.log(yourObject[i].values);
    console.log(yourObject[i].input);
}

Upvotes: 1

Josh
Josh

Reputation: 3288

You're looking for $.each. This will allow you to loop through object-arrays.

https://api.jquery.com/jquery.each/

If you're also asking how to capture the values and you have the raw text, you're also looking for $.parseJSON

https://api.jquery.com/jquery.parsejson/

Upvotes: 0

Related Questions