Jquery从嵌套数组中选择值

时间:2013-03-06 11:08:07

标签: jquery arrays getjson

我需要从嵌套数组中选择值,这是我的代码,

<!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>

这是我的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
        }
    }
]}

输出:

line1
line2
undefined,undefined

这是我得到的输出,但我需要显示名字和姓氏。

1 个答案:

答案 0 :(得分:1)

您需要将data.users而不是data传递给每个功能。数据是一个对象,其中array名为users,您可能想要迭代。

<强> Live Demo

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