4 回答
TA贡献1829条经验 获得超6个赞
let find = (array, label) =>{
let stack = [];
let going = true;
let walker = (array, label) => {
array.forEach(item => {
if (!going) return;
stack.push(item['label']);
if (item['label'] === label) {
going = false;
} else if (item['children']) {
walker(item['children'], label);
} else {
stack.pop();
}
});
if (going) stack.pop();
}
walker(array, label);
return stack.join('-');
}
console.log(find(data, '三级 3-2-2'))
// 一级 2-二级 2-2-三级 3-2-2
应该是 DFS
TA贡献1725条经验 获得超7个赞
目测lz遇到的问题是树形选择器,某个节点被选中后希望拿到该节点的层级信息,目前找到比较好的方案是拿到数据后遍历一遍,在每一个节点上生成一个levelInfo字段,标识当前层级信息。
[{
projectid: 110000,
name: "一级 1",
levelInfo: "110000"
children: [{
projectid: 110100,
name: "二级 1-1",
levelInfo: "110000-110100"
children: [{
projectid: 110101,
name: "三级 1-1-1",
children: null,
levelInfo: "110000-110100-110101"
}, {
projectid: 110102,
name: "三级 1-1-2",
children: null,
levelInfo: "110000-110100-110102"
}]
}, {
projectid: 110200,
name: "二级 1-2",
levelInfo: "110000-110200"
children: [{
projectid: 110201,
name: "三级 1-2-1",
children: null,
levelInfo: "110000-110200-110201"
}, {
projectid: 110202,
name: "三级 1-2-2",
children: null,
levelInfo: "110000-110200-110202"
}]
}]
}]
// 生成该结构的函数,希望可以帮到你
function formatTree(arr, levelInfo = '') {
return arr.map(item => {
const newParent = levelInfo ? levelInfo + '-' + item.projectid : '' + item.projectid;
const temp = {
...item,
levelInfo: newParent
};
if (item.children) {
temp.children = formatTree(item.children, newParent);
}
return temp;
})
}
TA贡献1998条经验 获得超6个赞
const getParent = (data, target) => {
const get = (children, target, record = []) => (
children.reduce((result, { label, children: innerChildren }) => {
if (label === target) {
return [...record, target]
}
if (innerChildren) {
return [...result, ...get(innerChildren, target, [...record, label])]
}
return result
}, []))
return get(data, target).join('-')
}
// 一级 2-二级 2-1-三级 3-1-2
const str = getParent(data, '三级 3-1-2')
添加回答
举报