这是我正在谈论的 JSON,
{
"0": {
"entry_id": "4",
"category_id": "3",
"title": "lorem ipusm"
},
"1": {
"entry_id": "5",
"category_id": "3",
"title": "lorem ipusm dolor"
},
......
......
"total_entry": 270,
"pending": 7,
"url": "http://domainhere.tld/url"
}
我需要读取total_entry、pending等字段的值。然后还需要迭代所有具有0,1等键的对象(可以继续,本例中只显示了两个。这就是我正在努力
var makelist;
for (var i = 0; i < objData.length; i++) {
makelist='<li>'+ objData[i].title + '</li>';
}
$('#conatiner').append(makelist);
它适用于获取带有 0,1 之类的键的对象,但仅当 json 不包含其他字段(total_entry 等..)时。我如何读取这两个字段?
最佳答案
使用jQuery each iterate function迭代对象。
Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
比每个不的属性/键Not-a-Number添加新列表项:
var obj = {
"0": {
"entry_id": "4",
"category_id": "3",
"title": "Title for item 0"
},
"1": {
"entry_id": "5",
"category_id": "3",
"title": "Title for item 1"
},
"total_entry": 270,
"pending": 7,
"url": "http://domainhere.tld/url"
};
var makelist = '';
$.each(obj, function( i, n ) {
if ( !isNaN(parseInt(i)) ) makelist+='<li>'+ n.title + '</li>';
});
$('#container').append(makelist);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="container"></ul>
关于javascript - 遍历 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29163608/