user2536281
user2536281

Reputation:

Iterating JSON array using jQuery

I have a JSON array ( partial data).

   {
      "person1": { "firstName":  "Joe", "lastName":"Dutonz"},
      "person2": { "firstName":  "Joe", "lastName":"Foo"},
etc
    }

The requirement is to loop through the JSON array and display all the firstName of the people data.

$.getJSON("people.json", function(obj)
 {
    loop through people data and display firstName
});

Using jQuery how to fetch firstName?

Upvotes: 0

Views: 92

Answers (2)

user2488066
user2488066

Reputation:

Use .each() function to loop through the key value pairs and display the value as shown below.

$.getJSON("people.json", function(obj){   
     $.each(obj, function(key,value){
         alert(value.firstName);
     });
});

Upvotes: 1

James
James

Reputation: 82096

This is what the for iterator was designed for e.g.

$.getJSON("people.json", function(obj)
{
    for (var propName in obj)
    {
        console.log(obj[propName]);
    }
});

Upvotes: 3

Related Questions