javascript - 遍历 json 值

标签 javascript jquery json

这是我正在谈论的 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/

相关文章:

javascript - ReactJS 组件的 OnChange 事件未在 IE 11 上触发

jquery - 关闭 jquery 后启用悬停

javascript - 如何将表格导出到 Excel

php - Android JSONParsing 错误 : E/Buffer Error﹕ Error converting result java. lang.NullPointerException: lock == null

javascript - 从数据库存储和检索时 FullCalendar 日期不同

javascript - div的多种背景颜色

jquery - 如何使用 jQuery 只选择一行表

javascript - Web Components,将数据传入和传出

javascript - 如何将 datepicker 日期转换为 JSON 对象以在 AJAX 请求中使用

javascript - 如何使 CodeMirror 从一定行数开始,并扩展到用户输入的行数?