树型数据的操作处理
备份一组数据:
1 let a = [ 2 3 {name:"1",id:"1",children:[{name:"1-1",id:"1-1",children:[{name:"1-1-1",id:"1-1-1"}]}]}, 4 {name:"2",id:"2",children:[{name:"2-1",id:"2-1",children:[{name:"2-1-1",id:"2-1-1"}]}]} 5 ]
1. 根据id找到节点
1 function getNodeById(list,id){ 2 for(let i in list){ 3 if(list[i].id===id){ 4 return list[i] 5 } 6 if(list[i].children&&list[i].children.length){ 7 let find = getNodeById(list[i].children,id); 8 if(find){ 9 return find; 10 } 11 } 12 } 13 }
2. 根据id找到所有的父节点
1 function getParentsById(list,id){ 2 for(let i in list){ 3 if(list[i].id === id){ 4 return [list[i]] 5 } 6 if(list[i].children&&list[i].children.length){ 7 let node = getParentsById(list[i].children,id); 8 if(node){ 9 // return node.concat(list[i])
node.unshift(list[i]);
return node;
10 } 11 } 12 13 } 14 15 }
3. 只要一个子节点的属性expand为true,则父节点属性expand也为true
1 function dealExpand(nodeData) { 2 if (nodeData["children"] && nodeData["children"].length) { 3 nodeData["children"].forEach((one) => { 4 one["expand"] = dealExpand(one); 5 }); 6 return ( 7 nodeData["expand"] || 8 !!nodeData["children"].filter((one) => one["expand"]).length 9 ); 10 } else { 11 return nodeData["expand"]; 12 } 13 }
data.forEach(one=>{
one.expand = dealExpand(one);
})
4. 树的所有子节点check属性为true,则父节点的check也为true
1 function dealCheck(nodeData) { 2 if (nodeData["children"] && 4 nodeData["children"].length 5 ) { 6 nodeData["children"].forEach((one) => { 7 one["check"] = dealCheck(one); 8 }); 9 return ( 10 nodeData["children"].filter( 11 (one) => one["check"] 12 ).length === nodeData["children"].length 13 ); 14 } else { 15 return nodeData["check"]; 16 } 17}
data.forEach(one=>{
one.check = dealCheck(one);
})
5. 树的每个节点都增加属性custom
1 function addCustom(list){ 2 list.forEach(one=>{ 3 one.custom = "自定义"; 4 if(one.children&&one.children.length){ 5 addCustom(one.children) 6 } 7 }) 8 }
6. 根据id和pid将一维数组处理为树形数组
1 let list = [ 2 {name:"1",id:"1"}, 3 {name:"1-1",id:"1-1",pid:"1"}, 4 {name:"1-1-1",id:"1-1-1",pid:"1-1"}, 5 {name:"2",id:"2"}, 6 {name:"2-1",id:"2-1",pid:"2"} 7 ]
1 function dealOptions(list){ 2 let dealOptions = [] 3 // 给每个数据加children属性 4 list.forEach( one => { 5 one.children = [] 6 }) 7 list.forEach( one => { 8 let findIndex = list.findIndex(item => { 9 return item.id === one.pid 10 }) 11 if ((!one.pid && one.pid !== 0 && one.pid !== false) || findIndex === -1) { 12 dealOptions.push(one) 13 } else { 14 list[findIndex].children.push(one) 15 } 16 }) 17 return dealOptions 18 }