How to get an array of object values ​​using jquery

I have a problem to get the whole element in an array of an object using jquery ...

I get this code from the Internet ...

var id = 123;
var test = new Object();
test.Identification = id;
test.Group = "users";
test.Persons = new Array();

test.Persons.push({"FirstName":" AA ","LastName":"LA"});
test.Persons.push({"FirstName":" BB ","LastName":"LBB"});
test.Persons.push({"FirstName":" CC","LastName":"LC"});
test.Persons.push({"FirstName":" DD","LastName":"LD"});

How to get each of "FirstName" and "LastName" in Persons using jQuery ??

+3
source share
4 answers

You can use $.each()or $.map(), depending on what you want to do with it.

$.map(Persons, function(person) {
    return person.LastName + ", " + person.FirstName;
});
// -> ["Doe, John", "Appleseed, Marc", …]
+8
source

You can use $.each()to iterate over an array.

$.each(test.Persons, function(index){
    alert(this.FirstName);
    alert(this.LastName);
});

See working demo

+4
source

You can use JavaScript syntax for the array:

for(var i in test.Persons) {
    alert(test.Persons[i].FirstName + " " + test.Persons[i].LastName);
}
+1
source

Using jQuery for this will outwit imho a bit.

Array.forEach :

test.Persons.forEach(function(person) {
  alert(person.FirstName + " " + person.LastName);
});

or just by index:

alert(test.Persons[0].FirstName + " " + test.Persons[0].LastName);
0
source

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


All Articles