已知一个无序数组,有一个初始id根据这个初始ID 从数组中排出//处理后的结果
{tid:8836,child:[{tid:936,child:[...],tid:939...}]}//原始请求回来的数据
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]
}]求大佬们救命啊,我们后端不给处理,让我们自己处理一些对应关系的数组 整理成map类型的数据
7 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
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);
人到中年有点甜
TA贡献1895条经验 获得超7个赞
这就是个递归算法
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布斯
TA贡献1876条经验 获得超6个赞
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);
添加回答
举报
0/150
提交
取消