const data = [{
"id": 10,
"name": "phone",
"children": [
{
"id": 31,
"name": "cellphone",
"children": [
{
"id": 47,
"name": "android"
}
]
},
{
"id": 32,
"name": "landline"
}
]
},
{
"id": 12,
"name": "document"
},
{
"id": 90,
"name": "document-name",
"children": [
{
"id": 91,
"name": "new-name"
}
]
}]
const filterId = (data, id) => {
if(!Array.isArray(data)) {
return data
}
return data.filter(item => {
if ('children' in item) {
item.children = filterId(item.children, id)
}
return (item.id === undefined || item.id !== id)
})
}
console.log(JSON.stringify(data, null, 4))
const filtredData = filterId(data, 47)
console.log(JSON.stringify(filtredData, null, 4))
data的数据:![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/878f5ea9d9114b1c72c4e05bf41a9160.png)
删除后filtredData的数据:
注意:最外层一定要是数组,有的给的是对象,需要自己在最外层加上[],得到最后的结果后再取数据的[0]即可