需求说明:
递归遍历list,删除status为0的节点,如果一级节点status为0,其下面的节点都删除。(ps:会用在系统的权限控制中,当状态为0(不可见),不显示该节点)
解决方法:
var List = [
{ name: "节点1", status: 0 },
{
name: "节点2",
status: 1,
children: [
{ name: "节点2-1", status: 1 },
{ name: "节点2-2", status: 0 }
]
},
{
name: "节点3",
status: 1,
children: [
{ name: "节点3-1", status: 1 },
{ name: "节点3-2", status: 1 }
]
},
{ name: "节点4", status: 1 },
{
name: "节点5",
status: 0,
children: [
{ name: "节点5-1", status: 1 },
{ name: "节点5-2", status: 1 }
]
}
]
function removeZero(showlist) {
if (typeof showlist == "object") {
// 如果showList是一个object,遍历showlist
for (let i = 0; i < showlist.length; i++) {
let element = showlist[i]
if (element.status === 0) {
showlist.splice(i, 1)
// 注意删除了一项后,索引-1
i--
} else {
// 遍历其子节点
removeZero(element.children)
}
}
} else {
// 子节点不存在则结束
return
}
}
removeZero(List)
console.log(List)