3 回答

TA貢獻1802條經驗 獲得超4個贊
我猜你現有的解決方案就像
const data = [
{
key: '1',
title: 'title 1',
children: [{
key: '098',
title: 'hey',
children: [{ key: '677', title: 'child'}]
}]
},
{ key: '123', title: 'tile 111' },
{ key: '345', title: 'something' }
];
function removeByKey(arr, removingKey){
return arr.filter( a => a.key !== removingKey);
}
所以它在第一層起作用,但并不深入。
只要改變它就可以完成工作
function removeByKey(arr, removingKey){
return arr.filter( a => a.key !== removingKey).map( e => {
return { ...e, children: removeByKey(e.children || [], removingKey)}
});
}
小警告,對于沒有任何子項的每個項目,子項屬性不會設置為 []。
那么它是如何運作的呢?好吧,我們不是按原樣保留可接受的項目,而是使用與本例{...e}相同的內容來制作副本。{key:e.key, title:e.title, children:e.children}
我們知道用 強制覆蓋子屬性removeByKey(e.children || [], removingKey),因此我們遞歸地調用該方法。該功能的作用并不深入。

TA貢獻1842條經驗 獲得超21個贊
我會使用 findIndex 和 splice 的遞歸方法。使用some將允許代碼退出而不運行整個樹。
const data = [{
key: '1',
title: 'title 1',
children: [{
key: '098',
title: 'hey',
children: [{
key: '677',
title: 'child'
}]
}]
},
{
key: '123',
title: 'tile 111'
},
{
key: '345',
title: 'something'
}
];
const removeKey = (data, key) => {
// look to see if object exists
const index = data.findIndex(x => x.key === key);
if (index > -1) {
data.splice(index, 1); // remove the object
return true
} else {
// loop over the indexes of the array until we find one with the key
return data.some(x => {
if (x.children) {
return removeKey(x.children, key);
} else {
return false;
}
})
}
}
console.log(removeKey(data, '677'))
console.log(JSON.stringify(data));

TA貢獻1847條經驗 獲得超11個贊
您可以使用一些簡單的遞歸來實現這一點:
const data = [
{
key: '1',
title: 'title 1',
children: [
{
key: '098',
title: 'hey',
children: [{ key: '677', title: 'child'}]
}
]
},
{ key: '123', title: 'tile 111' },
{ key: '345', title: 'something' }
];
function removeByKey(key, arr) {
// loop through all items of array
for(let i = 0; i < arr.length; i++) {
// if array item has said key, then remove it
if(arr[i].key === key) {
arr.splice(i, 1);
} else if(typeof(arr[i].children) !== "undefined") {
// if object doesn't have desired key but has children, call this function
// on the children array
removeByKey(key, arr[i].children);
}
}
}
removeByKey('098', data);
console.log(data);
這可能比提供的其他答案更容易理解。
添加回答
舉報