我有以下模型对象:const model = { _id: '1', children: [ { id: '2', isCriteria: true }, { id: '3', isCriteria: true } ]}PS:孩子的深度是未知的,所以我必须使用递归函数来导航它。我想根据id数组从子数组中删除特定对象。因此,例如,如果进行以下调用,则结果应为:removeCriteria(model, ['2'])const model = { _id: '1', children: [ { id: '2', isCriteria: true } ]}我按如下方式实现了这个函数: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);}
1 回答
HUH函数
TA贡献1836条经验 获得超4个赞
赋值给 不会赋值到值来自的对象属性。parent
您需要筛选并分配回该属性。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);
添加回答
举报
0/150
提交
取消