-
慕虎7371278
我猜你现有的解决方案就像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),因此我们递归地调用该方法。该功能的作用并不深入。
-
茅侃侃
我会使用 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));
-
回首忆惘然
您可以使用一些简单的递归来实现这一点: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);这可能比提供的其他答案更容易理解。