[英]How to access and remove/delete a property within a nested Javascript object?
[英]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'
}
]
}]
}
有人可以幫忙嗎?
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.