使用jquery循环json多维数组时的困惑
我有这样的json数据使用jquery循环json多维数组时的困惑,jquery,json,Jquery,Json,我有这样的json数据 var menuItems = { data: { dataA: { cmClass: "classA", cmID: "a", properties: [ { cId: 'testa', cClass: 'edit', aId: 'sa', text: 'sample a' },
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' },
]
}
}
};
我想遍历所有数据,并从中创建一个无序列表。因此,为了测试im,使用以下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:[对象]”、“1:[对象]”等循环,我被困在这里,我尝试了不同的情况,但似乎没有任何效果。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]);
}
})
}
}
});
});
如果您使用
console.log
而不是alert
.thx.,则调试会容易得多。。这是个好主意。。。但实际问题的解决方案是什么?只有一个疑问,我如何才能像cmClass一样访问cmId,而不是从变量中进行一般访问?@Reuben当你知道父键时,你可以通过:menuItems.data.dataA.cmClassyes michel,我明白了。。但是如果我们是r循环,有可能在第二个循环中这样说吗?因为它对我来说是“未定义的”.抱歉之前的评论。。我把它放错地方了。。它工作得很好。。非常感谢:)