MAHI
MAHI

Reputation: 10163

Jquery select value from nested array

i need to select values from a nested array, here is my code for this,

<!DOCTYPE html>
<html>
<head>
<script src="jquery.js">
</script>
<script>
$(document).ready(function(){
    $.getJSON('userdetails.json', function(data) {
        $.each(data, function(i,obj){
            $("#placeholder").append('<p>'+obj.firstName+","+obj.lastName+'</p>');
        });
    });
});
</script>
</head>
<body>
<div id="placeholder">
<p>line1</p>
<p>line2</p>
</div>
</body>
</html>

and here is my userdetails.json

{"users":[
    {
        "firstName":"user1",
        "lastName":"lastname1",
        "joined": {
            "month":"January",
            "day":12,
            "year":2012
        }
    },
    {
        "firstName":"user2",
        "lastName":"lastname2",
        "joined": {
            "month":"April",
            "day":28,
            "year":2010
        }
    }
]}

output:

line1
line2
undefined,undefined

this is the output which i get but i need to display firstname and lastname.

Upvotes: 1

Views: 210

Answers (1)

Adil
Adil

Reputation: 148120

You need to pass data.users instead of data to each function. Data is an object which has array named users which you probably want to iterate.

Live Demo

$.each(data.users, function (i, obj) {
    $("#placeholder").append('<p>' + obj.firstName + "," + obj.lastName + '</p>');
});

Upvotes: 1

Related Questions