2017-03-28 11 views
0

ここでアルゴリズムのスキルが終了します。私はオブジェクトを通過して特定のオブジェクトを見つけることができますが、同時にオブジェクトを削除することはできません。ここで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' 
      } 
     ] 
    }] 
} 

です。私はそれを見つけて、そのキーを含むオブジェクトを削除したい。

出力は、そのようにする必要があります:

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などの

答えて

3

アレイ法は、ここに便利になることができます:return文でフィルタを組み合わせる

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%; }

+1

をミッシングリンクでした。ありがとう@ –

関連する問題