1. Define an array first, and store objects in the array. The object contains a child array, and the level is variable, as follows:
let arr = [
{
id: 1,
name: '李渊',
age: 100,
children: [
{ id: 2, name: '李建成', age: 80, children: [] },
{
id: 3,
name: '李世民',
age: 70,
children: [
{id: 5, name: '李承乾', age: 50},
{id: 6, name: '李宽', age: 40},
{id: 7, name: '李恪', age: 30},
]
},
{ id: 4, name: '李玄霸', age: 65, children: [] }
]
},
]
2. Realize the deletion of data that meets the conditions, such as deletion of "age<60";
// 递归删除数组中符合条件的元素,并返回新数组
function handleData(array) {
return array.reduce((prev, item, index) => {
if (item.age < 60) {
return prev
}
prev[index] = item
if (item.children) {
prev[index].children = this.handleData(item.children)
}
return prev
}, [])
}
3. Call this method and the return result is as follows:
Welcome everyone to consult. If you have a simpler method, you can share it in the comment area, thank you!