这是我第一次尝试在javascript中使用递归时,我需要一些帮助来理解它。
我有这个JSON,有多个级别的“子类别”
var STORE_CATEGORIES = [{
"Id":"1",
"Name":"One Parent",
"Sort":"0",
"Subcategories":[
"Id":"1",
"Name":"One Subcategory",
"Sort":"0",
"Subcategories":[{
"Id":"1",
"Name":"One SubSubcategory",
"Sort":"0",
"Subcategories":[{
.....
}]
}]
]},
"Id":"2",
"Name":"Two Parent",
"Sort":"1",
....
]}
这是我的脚本,直到现在:
function sortJSON(json, output, prop, asc){
json = json.sort(function(a, b){
if(asc){
return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
} else {
return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
}
});
showJsonResults(json, output);
}
function showJsonResults(json, output){
var parent = output;
var list = $('<ul />').appendTo(parent);
var html = '';
for (var i = 0; i < json.length; i++) {
var result = json[i];
html += '<li data-sort="'+result.Sort+'" data-id="'+result.Id+'"';
if(result.Visible == false){
html += ' class="hide"';
}
html += '><a href="'+result.URL+'">'+result.Name+'</a>';
if(result.Subcategories){
html += '<ul>';
for (key in result.Subcategories) {
var sub = result.Subcategories[key];
html += '<li data-sort="'+sub.Sort+'" data-id="'+sub.Id+'"';
if(sub.Visible == false){
html += ' class="hide"';
}
html += '><a href="'+sub.URL+'">'+sub.Name+'</a>';
html += '</li>';
}
html += '</ul>';
}
html += '</li>';
}
list.append(html);
}
致电功能:
sortJSON(STORE_CATEGORIES, $('.categories div'), 'Sort', true);
现在我只获得了类别+子类别,但是子类别还有更多子类别。
我如何在这里使用递归? 感谢。
答案 0 :(得分:1)
您需要稍微改变一下您的功能:
function sortJSON(json, output, prop, asc){
json = json.sort(function(a, b){
if(asc){
return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
} else {
return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
}
});
var parent = output;
var list = $('<ul />').appendTo(parent);
var html = showJsonResults(json);
list.append(html);
}
function showJsonResults(json) {
var html = '';
$.each(json, function(i, result) {
html += '<li data-sort="' + result.Sort + '" data-id="' + result.Id + '"';
if (result.Visible == false) {
html += ' class="hide"';
}
html += '><a href="' + result.URL + '">' + result.Name + '</a>';
if (result.Subcategories.length) { //if you have subcategories call the function again
console.log(result.Subcategories[0].Name);
html += '<ul>' + showJsonResults(result.Subcategories) + '</ul>';
}
html += '</li>';
});
return html
}
}