3

i have problem to get all element in array of object using jquery...

i get this code from 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??

4 Answers 4

8

You could 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", …]
Sign up to request clarification or add additional context in comments.

Comments

4

You can use $.each() to iterate through the array.

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

See a working demo

Comments

1

You can use JavaScript syntax for array:

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

Comments

0

Using jQuery for that is a little overkill imho.

Array.forEach:

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

or simply by index:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.