问题描述
这是,其中我通过标识parentActivityId将对象推入数组。
现在我想根据其ID删除该对象。我已根据后续问题尝试了以下代码,但它不起作用。有人可以告诉我我在做什么错吗?
This is a follow up of Pushing an object into array where I was pushing an object into the array by identifying the parentActivityId.Now I wanted to remove the object based on its id.I have tried the below code based on the follow up question but its not working.Can anyone tell me what I'm doing wrong here?
function getParent(r, a) {
return a.id === child.parentActivityId ? a : a.items.reduce(getParent, r);
}
var node = data.reduce(getParent, {});
'items' in node && node.items.splice(child,1);
推荐答案
此解决方案具有以递归的方式进行一些基本的错误处理。
This solution features Array.prototype.some()
in a recursive fashion with some basic error handling.
The data is taken from Not able to push an object into parent array by identifying the parent id of the object in javascript.
关键功能是用于查找所需节点和索引的回调。
The key feature is the callback for finding the needed node and the index.
var data = [{ id: 1, activityName: "Drilling", parentActivityId: 0, items: [{ id: 2, activityName: "Blasting", parentActivityId: 1, items: [{ id: 3, activityName: "Ann", parentActivityId: 2, items: [] }, { id: 4, activityName: "Ann", parentActivityId: 2, items: [] }] }, { id: 5, activityName: "Transport", parentActivityId: 1, items: [{ id: 6, activityName: "Daniel", parentActivityId: 5, items: [] }] }] }],
id = 3,
node;
function findNode(a, i, o) {
if (a.id === id) {
node = { array: o, index: i };
return true;
}
return Array.isArray(a.items) && a.items.some(findNode);
}
data.some(findNode);
if (node && Array.isArray(node.array)) {
node.array.splice(node.index, 1);
}
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
这篇关于根据javascript中的ID删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!