jquery - 使用 jquery 循环 json 多维数组的困惑

标签 jquery json

我有一个像这样的json数据,

var menuItems = {
    data:
    {        
        dataA: 
        {
            cmClass: "classA",
            cmID: "a",
            properties: [
                { cId: 'testa', cClass: 'edit', aId: 'sa', text: 'sample a' },
                { cId: 'testaa', cClass: 'cut', aId: 'saa', text: 'sample aa' }                
            ]
        },
        dataB: 
        {
            cmClass: "classB",
            cmID: "b",
            properties: [
                { cId: 'testb', cClass: 'edit', aId: 'sb', text: 'sample b' },
                { cId: 'testbb', cClass: 'cut', aId: 'sbb', text: 'sample bb' },
                { cId: 'testbbb', cClass: 'copy', aId: 'sbbb', text: 'sample bbb' },
            ]
        }
    }
};

我想循环遍历所有数据并从中创建一个无序列表。因此,为了测试我有以下 jquery,

    $.each(menuItems.data, function (i) {
    $.each(this, function (key, value) {
    {
        alert(key + " : " + value);
        if (key == "properties") {
            $.each(value, function (key1, value1) {
                alert(key1 + " : " + value1);
            })
        }
    }
    });          
});

第一个警报正确显示为“cmClass:classA”、“cmId:a”等,但第二个循环始终给出“0:[object object]”、“1:[object object]”等.,我被困在这里,我尝试了不同的情况,但似乎没有任何效果。是不是json数据有问题?有人可以帮忙吗?我被困在这里

最佳答案

您循环遍历对象,因此您需要在 $each 内执行另一个循环。

$.each(menuItems.data, function (i) {
    $.each(this, function (key, value) {
    {
        console.log(key + " : " + value);
        if (key == "properties") {
            $.each(value, function (key1, value1) {
                for(k in value1) {
                   console.log( key1 + ':' + k + ':' + value1[k]);
                }
            })
        }
    }
    });
});

关于jquery - 使用 jquery 循环 json 多维数组的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14871683/

相关文章:

javascript - sweetalert2 未捕获语法错误 : Unexpected identifier

javascript - json.js 和 json2.js 有什么用?

java - 如何创建json解析的模型类?

php - 从 YouTube API v3 中的播放列表获取所有视频信息

JSONPath - 获取对象 othervalue 等于字符串的所有值

javascript - 悬停时的语义 Ui 下拉菜单

javascript - 将 div 固定到屏幕

php - json_encode 将数组转为对象

javascript - View 更改时 Backbone 重新加载 slider ?

javascript - JQuery ProgressBar 更改默认颜色