Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each function for single and multiple elements

Tags:

json

jquery

each

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.

like image 900
bmw0128 Avatar asked May 14 '13 18:05

bmw0128


2 Answers

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/

like image 176
Explosion Pills Avatar answered Nov 14 '22 12:11

Explosion Pills


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){...
like image 4
Kevin B Avatar answered Nov 14 '22 12:11

Kevin B