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的数据:
删除后filtredData的数据:
注意:最外层一定要是数组,有的给的是对象,需要自己在最外层加上[],得到最后的结果后再取数据的[0]即可