簡體   English   中英

如何在JavaScript中刪除嵌套對象樹中的特定節點

[英]How to delete particular nodes within a nested object tree in JavaScript

這就是我的算法技能的結局。 我可以遍歷對象並找到某個對象,但無法同時刪除該對象。

這是對象

const obj = {
    children: [{
        children: [
            {
                children: [
                    {
                        key: 'a1',
                        type: 'a1_type'
                    },
                    {
                        key: 'a2',
                        type: 'a2_type'
                    }
                ],
                key: 'root',
                type: 'root_type'
            },
            {
                key: 'error',
                type: 'error_type'
            }
        ]
    }]
}

鍵為==='error'對象的對象可以位於任何子數組中。 我想找到它並刪除包含密鑰的對象。

輸出應該是這樣的:

let output = findAndDeleteObjByKeyAndType('error', 'error_type')

output = {
    children: [{
        children: [
            {
                children: [
                    {
                        key: 'a1',
                        type: 'a1_type'
                    },
                    {
                        key: 'a2',
                        type: 'a2_type'
                    }
                ],
                key: 'root',
                type: 'root_type'
            }
        ]
    }]
} 

有人可以幫忙嗎?

陣列的方法,如filterevery可以在這里派上用場:

 const object = { children: [{ children: [{ children: [{ key: 'a1', type: 'a1_type' }, { key: 'a2', type: 'a2_type' }, { key: 'error', type: 'error_type' } ], key: 'root', type: 'root_type' }, { key: 'error', type: 'error_type' } ] }] } function purgeAll (object, target) { if (object.children) { const keys = Object.keys(target) object.children = object.children.filter(o => !keys.every(k => target[k] === o[k]) && purgeAll(o, target) ) } return object } let output = purgeAll(object, { key: 'error', type: 'error_type' }) console.log(output) 
 .as-console-wrapper { min-height: 100%; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM