项目中要求tree型的json数据按照json的某个字段对子节点进行排序,自己花时间写了写,整理如下:
要求:按照type属性对json数据进行排序,没有子节点(type=0)的排在前面
1.初始效果图和排序后效果图
1.嵌套子节点的json数据:
var data = [{"id":1,"name":"陕西省","type":1,children:
[ {"id":11,"name":"延安市","type":0,"state":"open"},
{"id":12,"name":"西安市","type":1,children:
[ {"id":121,"name":"长安区","type":1,children:
[{"id":1211,"name":"蓝田镇","type":1,children:
[
{"id":12113,"name":"武安村","type":1,children:
[{"id":121131,"name":"456号","type":1},
{"id":121132,"name":"458号","type":0},
{"id":121133,"name":"477号","type":0}
]
},
{"id":12111,"name":"爱丽村","type":1,"state":"closed"},
{"id":12112,"name":"玫瑰村","type":0}
]
},
{"id":1212,"name":"西斯镇","type":0}
]
},
{"id":122,"name":"雁塔区","type":0},
{"id":123,"name":"莲湖区","type":0}
]
},
{"id":13,"name":"宝鸡市","type":0,"state":"closed"},
{"id":14,"name":"汉中市","type":0,"state":"closed"},
{"id":15,"name":"渭南市","type":1,children:
[ {"id":151,"name":"临渭区","type":1,children:
[ {"id":1511,"name":"前进路","type":0},
{"id":1512,"name":"东风街","type":0},
{"id":1513,"name":"西四路","type":0}
]
},
{"id":152,"name":"大荔县","type":0},
{"id":153,"name":"华县","type":0}
]
}
]
}]
2.排序函数
$(function(){
$("#tree").tree({
data:data,
formatter:function(node){
return node.name;
},
loadFilter:function(data){
var len = data.length;
for(var i = 0;i < len;i++){
//使用匿名函数
(function(){
//arguments[0]指的是函数的第一个参数,此处为data[0],即陕西省这一父节点的json格式数据
var jsonArray = arguments[0];
for(var k in jsonArray){
//排序的条件:①存在子节点②子节点的个数大于1
if(k.indexOf('children')!=-1&&jsonArray[k]!=null){
if(jsonArray[k].length>1){
jsonArray[k] = jsonArray[k].sort(function(a,b){
return a.type > b.type? 1 : -1;
});
}
console.log("递归前");
//递归的条件①有子节点②父节点的类型为1
console.log(jsonArray);
if(jsonArray[k].length>0&&jsonArray.type==1){
console.log("递归");
for(var j = 0;j<jsonArray[k].length;j++){
//子节点类型如果为0,退出本次循环
if(jsonArray[k][j].type==0){
continue;
}
console.log("diguio");
//递归调用匿名函数
arguments.callee(jsonArray[k][j]);
}
}
}
}
})(data[i]);
return data;
}
}
});
});