使用实例删除javascript中基于id的对象

Deleting an object based on the id in javascript

本文关键字:id 对象 实例 删除 javascript      更新时间:2023-09-26

这是将对象压入数组的后续操作,我通过识别parentacvityid将对象压入数组。现在我想根据对象的id删除它。我已经尝试了下面的代码基于后续问题,但它不工作。有人能告诉我我哪里做错了吗?

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);

此解决方案以递归方式使用Array.prototype.some(),并具有一些基本的错误处理。

数据取自javascript中不能通过识别对象的父id将对象推入父数组

关键特性是用于查找所需节点和索引的回调。

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>');

您需要在父项数组中查找子节点的索引。应该像循环遍历父元素的items数组一样简单,直到遇到子元素id。

一旦你有了子节点的索引,使用它作为拼接函数的第一个参数

见下面的一个粗略的例子(你需要添加错误检查代码等的情况下,没有找到父或子)

function getParent(r, a) {
    return a.id === child.parentActivityId ? a : a.items.reduce(getParent, r);
}
var node = data.reduce(getParent, {});
var theChildIndex = 0;
for (i = 0; i < node.items.length; i++) { 
   if (node.items[i].id == child.id)
   {
       theChildIndex = i;
       break;
   }
}
node.items.splice(theChildIndex,1);