-
慕后森
用数组push方法,符合规律的组成一组,然后JSON的两个方法把弄,剩下就是拼接字符串
-
慕盖茨4494581
var begin_id = 8836;
var sub_list = [{
tid: 8836,
sub: [936, 939, 972]
}, {
tid: 936,
sub: [872, 811]
}, {
tid: 939,
sub: [762, 755, 703]
}, {
tid: 972,
sub: [644, 691, 672]
}, {
tid: 872,
sub: [544]
}, {
tid: 811,
sub: [435, 435, 435, 435, 435]
}];
function myFind(id) {
for (var i = 0, len = sub_list.length; i < len; i++) {
if (sub_list[i].tid == id) {
return sub_list[i];
}
}
return -1;
}
function createObj(begin_id) {
var tempObj = {};
var temp = myFind(begin_id);
if (temp != -1) {
tempObj.tid = temp.tid;
tempObj.child = [];
if (temp.sub && temp.sub.length > 0) {
for (var i = 0, len = temp.sub.length; i < len; i++) {
tempObj.child.push(createObj(temp.sub[i]));
}
}
}
return tempObj;
}
createObj(begin_id);
-
人到中年有点甜
这就是个递归算法var begin_id = 8836;
var sub_list = [{
tid: 8836,
sub: [936, 939, 972]
}, {
tid: 936,
sub: [872, 811]
}, {
tid: 939,
sub: [762, 755, 703]
}, {
tid: 972,
sub: [644, 691, 672]
}, {
tid: 872,
sub: [544]
}, {
tid: 811,
sub: [435, 435, 435, 435, 435]
}]
function convert(id) {
var so = sub_list.filter(function(v){
return id == v.tid;
})[0];
return so ? {
tid: so.tid,
child: so.sub.map(function(v){
return convert(v);
})
} : id;
}
var obj = convert(begin_id);
console.log(JSON.stringify(obj,null,4));
-
HUX布斯
var begin_id = 8836;
var sub_list = [{
tid:8836,
sub:[936,939,972]
},{
tid:936,
sub:[872,811]
},{
tid:939,
sub:[762,755,703]
},{
tid:972,
sub:[644,691,672]
},{
tid:872,
sub:[544]
},{
tid:811,
sub:[435,435,435,435,435]
}]
function createFindByIdArray(arr){
return function findById(id) {
return arr.filter(item=>item.tid===id);
}
}
const subArrFind=createFindByIdArray(sub_list);
function createTreeObject(id,obj={}){
const arr=subArrFind(id);
if(arr.length){
const item=arr[0];
obj['tid']=item.tid;
if(item.sub.length){
obj.child=[];
for(let i of item.sub){
obj.child.push(createTreeObject(i));
}
}
}else{
obj['tid']=id;
}
return obj;
}
const result=createTreeObject(begin_id);
console.log(result);
-
慕田峪9158850
把const let改成var 函数参数里的xx={} 放到函数里就行了
-
翻过高山走不出你
楼主,这是后端返回给你的数据吗,如果是,js会自动转成对象的呀,你直接遍历就行