先来看一个项目中常见的结构:
const tree = {
id: 0,
children: [
{
id: 1, children: [], title: '1'
}, {
id: 2, children: [], title: '2'
}, {
id: 3, children: [
{
haObj: {o1: 1},
arr: [1, 2, 3],
haha: "test",
id: 4, children: [], title: '4'
}
], title: '3'
},
]
}
我们经常需要做这样一个操作,根据查找tree里的某个节点,比如说找到id为4的节点,并返回当前节点,最普通的办法就是遍历:
function fun0(tarId, node) {
for(let item of node) {
if(item.id==tarId) {
return item
} else if(item.children.length) {
return fun0(tarId, item.children)
}
}
}
console.log(fun0(4, [tree]))
但是如果结构再复杂些,或者层级非常多的话,就会很消耗时间。如果层级能变成1的话,会省去很多时间。
以下是两种解决办法,转为字符串,根据字符匹配找到当前节点