1.根据子id 递归查找所有父级 id 主要用于vue element 中 Cascader 级联选择器展示 在编辑中回显默认展示
tree 数据
var arr = [{ "label": "文件夹", "parentId": null, "id": "0", "children": [{ "label": "文件夹1", "parentId": "0", "id": "1", "children": [{ "label": "文件夹1-1", "parentId": "1", "id": "1.1", "children": null }, { "label": "文件夹1-2", "parentId": "1", "id": "1.2", "children": null }, { "label": "文件夹1-3", "parentId": "1", "id": "1.3", "children": [{ "label": "文件夹1-3-1", "parentId": "1.3", "id": "1.3.1", "children": [{ "label": "文件夹1-3-1-1", "parentId": "1.3.1", "id": "1.3.1.1", "children": null }] }, { "label": "文件夹1-3-2", "parentId": "1.3", "id": "1.3.2", "children": null }, { "label": "文件夹1-3-3", "parentId": "1.3", "id": "1.3.3", "children": null } ] } ] }, { "label": "文件夹2", "parentId": "0", "id": "2", "children": [{ "label": "文件夹2-1", "parentId": "2", "id": "2.1", "children": null }] }, { "label": "文件夹3", "parentId": "0", "id": "3", "children": null } ] }];
递归查找
//递归找父级id getParentIds(treeData, nodeId) { var arrRes = []; if(treeData.length == 0) { if(!!nodeId) { arrRes.unshift(nodeId); } return arrRes; } let rev = (data, nodeId) => { for(var i = 0, length = data.length; i < length; i++) { let node = data[i]; if(node.id == nodeId) { arrRes.unshift(nodeId); rev(treeData, node.parentId); break; } else { if(!!node.children) { rev(node.children, nodeId); } } } return arrRes; }; arrRes = rev(treeData, nodeId); return arrRes; },
结果
console.log(getParentIds(arr,'1.3.1')) //["0", "1", "1.3", "1.3.1"]
2. 删除children:[] 存在且为空的情况 主要用于vue element 中 Cascader 级联选择器展示
var tree = [{ value: 'ziyuan', label: '资源', children: [ { value: 'axure', label: 'Axure Components', children: [] }, { value: 'sketch', label: 'Sketch Templates', children: [] }, { value: 'jiaohu', label: '组件交互文档', children: [] } ] }, { value: 'zujian', label: '组件', children: [ { value: 'layout', label: 'Layout 布局', children: [] }, { value: 'icon', label: 'Icon 图标', children: [] } ] } ]; function render(arr) { for(let i = 0; i < arr.length; i++) { if(arr[i] && arr[i].children.length == 0) { delete arr[i].children } if(arr[i].children && arr[i].children.length > 0) { render(arr[i].children) } } return arr }console.log(render(tree))//打印如下:已经删除空的children
来源:https://www.cnblogs.com/zhaozhenzhen/p/10972931.html