自定义一个树型的数据
const tree = [{
value: 1, label: "1",
children: [{
value: 11, label: "1-1",
children: [{
value: 111, label: "1-1-1"
}]
}]
}, {
value: 2, label: "2"
}]
保留指定层级的方法
function keepNodesAtLevel(data, level) {
if (level == 1) {
return data.map((node) => {
return {
value: node.value,
label: node.label
}
})
}
let result = []
for (let i = 0; i < data.length; i++) {
let node = data[i]
if (node.children) {
node.children = keepNodesAtLevel(node.children, level - 1)
}
result.push(node)
}
return result
}
console.log(keepNodesAtLevel(tree, 1))