[英]Remove object from array inside a recursive function
I have the following model object:我有以下 model object:
const model = {
_id: '1',
children: [
{
id: '2',
isCriteria: true
},
{
id: '3',
isCriteria: true
}
]
}
PS: The depth of children is unknown, so I have to use a recursive function to navigate through it. PS:children的深度未知,所以我必须使用递归的function来导航。
I want to delete specific objects fro children array based on the array of ids.我想根据 ids 数组从子数组中删除特定对象。
So for example if make the following call removeCriteria(model, ['2'])
, the result should be:因此,例如,如果进行以下调用removeCriteria(model, ['2'])
,结果应该是:
const model = {
_id: '1',
children: [
{
id: '2',
isCriteria: true
}
]
}
I implemented this function as follows:我实现了这个 function 如下:
function removeCriteria(node, criteria, parent = []) {
if (node.isCriteria) {
if (criteria.length && !criteria.includes(node.id)) {
parent = parent.filter(criteria => criteria.id !== node.id);
}
console.log(parent) // here the parents object is correct but it doesn't modify the original object
}
if (node.children)
for (const child of node.children) removeCriteria(child, criteria, node.children);
}
The issue is you're reassigning the variable parent
, which doesn't accomplish anything since you're not mutating the array to remove objects, and instead you're assigning it to a newly created array.问题是您正在重新分配变量parent
,这不会完成任何事情,因为您没有改变数组以删除对象,而是将其分配给新创建的数组。 I would suggest introducing a parentObj
reference to the object to which parent
belongs, so then you can set parentObj.children
to parent
and actually mutate the original object's array property:我建议引入对parent
所属的 object 的parentObj
引用,因此您可以将parentObj.children
设置为parent
并实际改变原始对象的数组属性:
const model = { _id: '1', children: [ { id: '2', isCriteria: true }, { id: '3', isCriteria: true } ] }; function removeCriteria(node, criteria, parent = [], parentObj = {}) { if (node.isCriteria) { if (criteria.length &&.criteria.includes(node.id)) { parent = parent.filter(criteria => criteria.id;== node.id); parentObj.children = parent, } console.log('parent'. parent) // here the parents object is correct but it doesn't modify the original object } if (node,children) for (const child of node,children) removeCriteria(child. criteria, node;children, node); } removeCriteria(model. ['2']); console.log(model);
Assigning to parent
doesn't assign to the object property where the value came from.分配给parent
级不会分配给值来自的 object 属性。
You need to filter node.children
and assign back to that property.您需要过滤node.children
并分配回该属性。
function removeCriteria(node, criteria) { if (criteria.length == 0) { return; } if (node.children) { node.children = node.children.filter(child =>.child.isCriteria || criteria.includes(child;id)). node.children,forEach(child => removeCriteria(child; criteria)): } } const model = { _id, '1': children: [{ id, '2': isCriteria, true }: { id, '3': isCriteria, true } ] } removeCriteria(model; ['2']). console;log(model);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.