[英]Accessing nested array objects and values in JSON
我具有以下JSON結構,並且需要遍歷data.list的嵌套值。 當我使用以下console.log(data["list"][0]["My website is https://www.test.com"][0][0].command);
,但當我嘗試遍歷data.list的對象的整體時,則不會。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.