0

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?

4
  • It does not looks like an array. Commented Jun 30, 2013 at 10:31
  • @SubirKumarSao ..not just looks like.. it is not an array at all... Commented Jun 30, 2013 at 10:32
  • @Subir , I have already mentioned that it is a partial data Commented Jun 30, 2013 at 10:33
  • Can you show at least two elements? Is it an array of objects or just a single object? Commented Jun 30, 2013 at 10:34

2 Answers 2

3

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]);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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);
     });
});

Comments

Your Answer

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