1

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.

1 Answer 1

1

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

2 Comments

thanks for your quick answer its works. but still i have to change each time in my script. is their exits any other way with out changing my scripts.
then help me to select the values of month,year,day.

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.