traversing jQuery JSON Object array

*爱你&永不变心* 提交于 2019-12-23 04:51:23

问题


I am try access an Object array using getJson, I've tried many things but I keep getting an 'undefined' or [Object, object] returned.

$.getJSON( "js/test.json", function( data ) {
    var items = new Array();
    $.each( data, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
    });

    $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
    }).appendTo( "body" );
});

Here is the JSON, I am trying to get the 'title' of each 'entries'.

{
"$xmlns": {
    "pl1": "url"
},
"startIndex": 1,
"author": "MJS",
"entries": [
    {
        "title": "This is target",
        "m$ct": [
            {
                "m$name": "name"
            }
        ],
        "m$rt": "pd",
        "m$content": [
            {
                "plfile$width": 640
            },
            {
                "plfile$width": 960
            }
        ],
        "plm$c": [],
        "link": ""
    },
    {
        "title": "title2",
        "m$ct": [
            {
                "m$name": "name"
            }
        ],
        "m$rt": "pd",
        "m$content": [
            {
                "plfile$width": 640
            },
            {
                "plfile$width": 960
            }
        ],
        "plm$c": [],
        "link": ""
    }
]
}

回答1:


$.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});

should instead read:

$.each( data.entries, function( key, entry ) {
    items.push( "<li id='" + key + "'>" + entry.title + "</li>" );
});



回答2:


You're iterating over the whole json instead of the entries

It should be data.entries in the each and then just val.title

$.getJSON( "js/test.json", function( data ) {
    var items = new Array();
    $.each( data.entries, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val.title + "</li>" );
    });

    $( "<ul/>", {
        "class": "my-new-list",
        html: items.join( "" )
    }).appendTo( "body" );
});


来源:https://stackoverflow.com/questions/20484014/traversing-jquery-json-object-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!