在JSON中访问嵌套的数组对象和值
问题描述:
我有以下JSON结构,我需要迭代data.list的嵌套值。当我使用下面的console.log(data["list"][0]["My website is https://www.test.com"][0][0].command);
进行硬编码时,我能够获得嵌套值,但是当我尝试迭代data.list的所有对象时,却无法获得嵌套值。在JSON中访问嵌套的数组对象和值
var data = {
"list": [
{
"The first website is https://www.w3.org/": [
[
{
"command": "This is dummy content",
"new": false,
"message": "This was fun to make"
}
]
]
},
{
"The second website is https://www.mozilla.org": [
[
{
"command": "This is the second command",
"new": true,
"message": "Lorem ipsum"
}
]
]
}
],
"verified": false
};
for (var i = 0; i < data.list.length; i++) {
// this doesn't work
console.log(data.list[i][0]["0"]["0"]).command;
}
答
您可以使用对象中的第一个键。
var data = { list: [{ "The first website is https://www.w3.org/": [[{ command: "This is dummy content", new: false, message: "This was fun to make" }]] }, { "The second website is https://www.mozilla.org": [[{ command: "This is the second command", new: true, message: "Lorem ipsum" }]] }], verified: false },
i;
for (i = 0; i < data.list.length; i++) {
console.log(data.list[i][Object.keys(data.list[i])[0]][0][0].command);
}
答
因为在列表中的项目是你在一个单独的循环遍历这些对象。此外,您必须考虑到它是一个对象,所以您应该使用对象属性作为索引而不是整数。
下应该工作:
for (var i = 0; i < data.list.length; i++) {
// this doesn't work
for (var property in data.list[i]) {
console.log(data.list[i][property][0][0].command);
}
}
你得到任何错误? –
为什么要将属性设置为任意字符串?你真的需要重新思考你的模式。 –
你的json非常奇怪,你每次都有一个1元素数组的1元素数组? – ValLeNain