我正在尝试使用jquery解析此JSON文件以访问设置为“true”的“onpage”字段。然后使用该项目中的其他字段(desc,icon,name& url)。我可以找到“项目”,但可以弄清楚如何在“项目”内进入“onpage”。 感谢
[
{
"group": "Home",
"url": "http://www.home.com/"
},
{
"group": "Production",
"items": [
{
"onpage": true,
"desc": "View local trails",
"icon": "img/trails.png",
"name": "Trails",
"url": "https://www.home.com/go/Trails"
},
{
"onpage": false,
"desc": "Edit local trail",
"icon": "img/traileditor.png",
"name": "Trail Editor",
"url": "https://www.home.com/go/Editor/"
}
]
}
答案 0 :(得分:1)
一旦解析了它,就会有一个包含两个对象的数组。这些对象中的第二个具有属性items
,它是一个对象数组。 items
数组中的第一个条目onpage
等于true
。所以直接路径是:
itemWithOnPageTrue = theParsedData[1].items[0];
如果你需要找到它,你可能会使用一对循环:
var itemWithOnPageTrue;
$.each(theParsedData, function() {
var found;
if (this.items) {
$.each(this.items, function() {
if (this.onpage) {
itemWithOnPageTrue = this;
found = true;
return false;
}
});
if (found) {
return false;
}
}
});
如果你返回false, $.each
将停止循环,这就是我们在找到第一个匹配时这样做的原因。如果你没有返回任何东西或返回不同的值,它将继续循环。
获得itemWithOnPageTrue
后,您可以访问其他属性,例如itemWithOnPageTrue.desc
,itemWithOnPageTrue.icon
等。