I have two types of JSON results:
{
"person":{
"fname": "Homer",
"lname": "Simpson"
}
}
{
"person":[
{
"fname": "Homer",
"lname": "Simpson"
},
{
"fname": "Marge",
"lname": "Simpson"
}
]
}
I want to use a jQuery "each":
$.each(response.person, function(i, person){...
but "i" and "person" are different when JSON has one vs. multiple persons. I see the single person response does not have the array "[]", but when I:
$.each([response.person], function(i, person){...
then the multiple persons does not work. I'm looking for a way to normalize things so that I may can use "each" consistently.
Ideally you would have an array given to you initially, but you can always .concat
the results to an empty array. This will allow you to loop consistently:
$.each([].concat(response.person), function(i, person){...
http://jsfiddle.net/MtzH8/
Test whether or not it is an array.
$.each(($.isArray(response.person) ? response.person : [response.person]), function(i, person){...
or you can modify the object prior to iteration:
if (!$.isArray(response.person)) {
response.person = [response.person];
}
$.each(response.person, function(i, person){...
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