以递归方式从对象中删除值列表 [英] Recursively delete a list of values from object
本文介绍了以递归方式从对象中删除值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ID列表
ids = [6,9]
和一个对象数组作为
data = {
"child": [{
"fruit": "apple",
"id": 1
},
{
"fruit": "mango",
"id": 2,
"child": [{
"name": "js",
"id": 4
}, {
"name": "jsk",
"id": 6
}]
},
{
"fruit": "banana",
"id": 9
}
]
}
我必须迭代数据才能找到id列表中存在id的任何对象。我必须要删除
I have to iterate over data to find any object with id present in list of ids.Here I have to delete
{"name":"jsk", "id": 6}
和
{"fruit":"banana","id":9}
要实现我已经写了以下代码
To achieve this I have written following code
deleteObj = (data, ids) => {
data.child.forEach((key, index) => {
if(key && ids.indexOf(child.id) > -1){
console.log("inside match before", key);
key.splice(index, 1);
console.log("inside match after: ", key);
}
if(key.child) {
deleteObj(key, ids);
}
})
};
但是在获得第一场比赛后的这个函数中它只是返回。只允许第一个匹配的id。
Pring only 在匹配之后:9
无法找到任何错误
But in this function after getting first match it simply return.Deliting only first matched id.
Pring only inside match after:9
Not able to find any error
推荐答案
您可以使用简单的而
循环并从最后进行迭代,因为拼接会删除实际索引并继续前进,得到一个未经处理的项目。
You could use a simple while
loop and iterate from the end, because splicing deletes the actual index and with moving on, you get an unprocessed item.
function deleteItems(array, ids) {
var i = array.length;
while (i--) {
if (ids.indexOf(array[i].id) !== -1) {
array.splice(i, 1);
continue;
}
array[i].child && deleteItems(array[i].child, ids);
}
}
var ids = [6, 9],
data = { child: [{ fruit: "apple", id: 1 }, { fruit: "mango", id: 2, child: [{ name: "js", id: 4 }, { name: "jsk", id: 6 }] }, { fruit: "banana", id: 9 }] };
deleteItems([data], ids)
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于以递归方式从对象中删除值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文