出个题考考你们
let tableList = [{
"guid": 1,
"name": "派大星",
"age": 18
},{
"guid": 3,
"name": "章鱼哥",
"age": 22,
"mapping": [{
"guid": 31,
"name": "海绵宝宝",
"age": 99
},{
"guid": 32,
"name": "珊迪",
"age": 55,
"mapping": [{
"guid": 321,
"name": "蟹老板",
"age": 99
}]
}]
},{
"guid": 5,
"name": "珍珍",
"age": 33,
}]
这是一个树形数据,问题(如何封装一个函数,传入的参数 1. 当前的树形数据 2. 数组,数组里面是树里面随机的id )
结果是删除这些id对应的 对象,并形成新的tree
fun( tableList, [1,321,5] ) => tree
注意: 这个函数是要用在vue里面的,是响应式哦
function useDeletWithId(tableList, ids) {
ids.forEach(id => {
tableList.some((item, index) => {
if (item.guid === id) {
return delete tableList[index]
} else {
item.mapping && useDeletWithId(item.mapping, [id])
}
})
})
}
function fun( tableList, ids ){
let list = []
tableList.forEach(item => {
if(!ids.includes(item.guid)){
let res = {...item}
if(Array.isArray(res.mapping)){
res.mapping = fun(res.mapping, ids)
}
list.push(res)
}
})
return list
}
let tableList = [{
"guid": 1,
"name": "派大星",
"age": 18
}, {
"guid": 3,
"name": "章鱼哥",
"age": 22,
"mapping": [{
"guid": 31,
"name": "海绵宝宝",
"age": 99
}, {
"guid": 32,
"name": "珊迪",
"age": 55,
"mapping": [{
"guid": 321,
"name": "蟹老板",
"age": 99
}]
}]
}, {
"guid": 5,
"name": "珍珍",
"age": 33,
}]
function deleteByIds(tableList, ids) {
function _deleteByIds(data, ids) {
if (!data || data.length == 0) {
return null
}
const result = data.filter(item => !ids.includes(item.guid));
result.forEach(item => item.mapping = _deleteByIds(item.mapping, ids))
return result;
}
return _deleteByIds(tableList, ids)
}
console.log(JSON.stringify(deleteByIds(tableList, [5, 321, 32])))