gpt4 book ai didi

javascript - 根据父值过滤嵌套的 JSON

转载 作者:行者123 更新时间:2023-11-30 20:55:03 26 4
gpt4 key购买 nike

我只想将基于父项的嵌套 JSON 打印到 HTML,但它始终显示所有值。JSON:

var json = {
"siteMap": [{
"title": "Red",
"link": "red.html",
"subPageArray": [{
"subTitle": "SubLink1",
"link": "test1.html"
}, {
"subTitle": "SubLink2",
"link": "test2.html"
}]
}, {
"title": "Blue",
"link": "blue.html",
"subPageArray": [{
"subTitle": "SubLink1",
"link": "test1.html"
}, {
"subTitle": "SubLink2",
"link": "test2.html"
}]
}, {
"title": "Green",
"link": "green.html"
}, {
"title": "Yellow",
"link": "yellow.html",
"subPageArray": [{
"subTitle": "SubLink1",
"link": "test1.html"
}, {
"subTitle": "SubLink2",
"link": "test2.html"
}]
}]
}

JavaScript 调用:

$.each(json.siteMap, function (i, val) {
var data="<li class='topLevel'><a href='/" + this.link + "'>" + this.title + "</a><ul>";
if(this.subPageArray!=undefined){ // to make sure subPageArray exists
for (i = 0; i < this.subPageArray.length; ++i) {
data += "<li class='subLevel'><a href='/" + this.subPageArray[i].link + "'>" + this.subPageArray[i].subTitle + "</a></li>";
}
}
data+="</ul></li>";

$(data).appendTo(".siteMapContent .hii");
});

和 HTML:

<div class="siteMapContent">
<ul class="hii"></ul>
</div>

如果我只想在 HTML 上打印 Blue 作为父级,如何过滤它?

fiddle :http://jsfiddle.net/zeef/va0zosuu/

非常感谢所有帮助。

最佳答案

好吧,您只需要检查迭代的 item 标题,如果它是 Blue 则显示它:

只需在你的循环中添加这个条件:

if (val["title"] === "Blue") {

演示:

var json = {
"siteMap": [{
"title": "Red",
"link": "red.html",
"subPageArray": [{
"subTitle": "SubLink1",
"link": "test1.html"
}, {
"subTitle": "SubLink2",
"link": "test2.html"
}]
}, {
"title": "Blue",
"link": "blue.html",
"subPageArray": [{
"subTitle": "SubLink1",
"link": "test1.html"
}, {
"subTitle": "SubLink2",
"link": "test2.html"
}]
}, {
"title": "Green",
"link": "green.html"
}, {
"title": "Yellow",
"link": "yellow.html",
"subPageArray": [{
"subTitle": "SubLink1",
"link": "test1.html"
}, {
"subTitle": "SubLink2",
"link": "test2.html"
}]
}]
};

$.each(json.siteMap, function(i, val) {
if (val["title"] === "Blue") {
var data = "<li class='topLevel'><a href='/" + this.link + "'>" + this.title + "</a><ul>";
if (this.subPageArray != undefined) { // to make sure subPageArray exists
for (i = 0; i < this.subPageArray.length; ++i) {
data += "<li class='subLevel'><a href='/" + this.subPageArray[i].link + "'>" + this.subPageArray[i].subTitle + "</a></li>";
}
}
data += "</ul></li>";

$(data).appendTo(".siteMapContent .hii");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div class="siteMapContent">
<ul class="hii"></ul>
</div>

注意:

否则更好的解决方案是使用 Array#filter() 过滤 json.siteMap 数组以仅获取具有 title:"Blue" 的数组 然后用 Array#forEach() 遍历它 并显示子项。

关于javascript - 根据父值过滤嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47753827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com