四级JSON数据
{
"Asia": [
{
"continentCode": "GT113",
"regionList": [
{
"regionName": "Eastern Asia",
"regionCode": "GR128",
"Countrylist": [
{
"countryName": "China",
"countryCode": "GC302",
"subCountryList": [
{
"subCountryName": "Southern China",
"subCountryCode": "GR206"
}
]
},
{
"countryName": "Hong Kong",
"countryCode": "GC303"
}
]
},
{
"regionName": "Southern Asia",
"regionCode": "GR134",
"Countrylist": [
{
"countryName": "India",
"countryCode": "GC304"
},
{
"countryName": "Pakistan",
"countryCode": "GC309"
}
]
}
]
}
]
我已将数据提取到 3 级并显示到 2 级。但是无法获取第 4 级数据并显示第 3 级和第 4 级数据。
$.each(json, function (i1, object) {
alert(i1);
$.each(object, function (i2, continent) {
$.each(continent.regionList, function (i3, region) {
alert(region.regionName);
$.each(region.Countrylist, function (i4, country) {
alert(country.countryName);
if (!$("ul." + i1).is("*")) {
$("<ul />", {
"class": i1,
"html": "<li>" + region.regionName + "</li>"
}).appendTo("div").before('<b class=' + i1 + ' ><a name="' + i1 + '" >' + i1 + '</a></b>');
}else{
$("b." + i1).each(function() {
var text = this.textContent || this.innerText;
if (text === i1) {
$(this).next("ul").append("<li>" + region.regionName + "</li>");
}
});
}
/* $.each(country.subCountryList, function (i5, subCountry) {
alert(subCountry.subCountryName);
}); */
});
});
});
});
})
<div>
<ul></ul>
</div>
如何获取其他显示如下
- 亚洲
东亚
中国 -
华南地区
香港
- 南亚
最佳答案
试试这个,使用@dimitar 的一些代码:
var json = {
"Asia": [{
"continentCode": "GT113",
"regionList": [{
"regionName": "Eastern Asia",
"regionCode": "GR128",
"Countrylist": [{
"countryName": "China",
"countryCode": "GC302",
"subCountryList": [{
"subCountryName": "Northern China",
"subCountryCode": "GR207"
}, {
"subCountryName": "Southern China",
"subCountryCode": "GR206"
}]
}, {
"countryName": "Hong Kong",
"countryCode": "GC303"
}]
}, {
"regionName": "Southern Asia",
"regionCode": "GR134",
"Countrylist": [{
"countryName": "India",
"countryCode": "GC304"
}, {
"countryName": "Pakistan",
"countryCode": "GC309"
}]
}]
}]
};
var html = '';
$.each(json, function(i1, object) {
html += '<li><b>' + i1 + '</b>';
$.each(object, function(i2, continent) {
html += '<ul>';
$.each(continent.regionList, function(i3, region) {
html += '<li><b>' + region.regionName + '</b>';
$.each(region.Countrylist, function(i4, country) {
html += '<ul><li>' + country.countryName;
if (country.subCountryList) {
html += "<ul>";
$.each(country.subCountryList, function(i5, subCountry) {
html += '<li>' + subCountry.subCountryName + '</li>';
});
html += "</ul>";
};
html += '</li></ul>';
});
html += '</li>';
});
html += '</ul>';
});
html += '</li>';
});
$('#list').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id='list'></ul>
关于javascript - 如何使用 jquery 遍历四级 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30512517/