JQuery each function for one and several elements

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 jQuery "every":

 $.each(response.person, function(i, person){... 

but "i" and "person" are different when JSON has one or more people. I see that the response of one person does not have an array [], but when I:

 $.each([response.person], function(i, person){... 

then a few people do not work. I am looking for a way to normalize things so that I can consistently use "everyone."

+6
source share
2 answers

Check if it is an array.

 $.each(($.isArray(response.person) ? response.person : [response.person]), function(i, person){... 

or you can change the object before iteration:

 if (!$.isArray(response.person)) { response.person = [response.person]; } $.each(response.person, function(i, person){... 
+4
source

Ideally, you will have an array provided to you initially, but you can always .concat get the results into an empty array. This will allow you to contact in sequence:

 $.each([].concat(response.person), function(i, person){... 

http://jsfiddle.net/MtzH8/

+6
source

Source: https://habr.com/ru/post/945003/


All Articles