【问题标题】:Deleting an object based on the id in javascript根据javascript中的id删除对象
【发布时间】:2015-11-14 22:05:40
【问题描述】:

这是Pushing an object into array 的后续行动,我通过识别 parentActivityId 将对象推送到数组中。 现在我想根据它的 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);

【问题讨论】:

  • 问一个“什么是正确的方法”的问题几乎是要求你的问题被否决。 :) 任何对你有用的方法都可能是正确的方法。问问自己代码是否按预期工作,没有副作用或错误。你了解它在做什么吗,其他人是否需要了解它在做什么。如果您对答案感到满意,那么它是适合您的方法..

标签: javascript arrays for-loop splice


【解决方案1】:

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

数据取自Not able to push an object into parent array by identifying the parent id of the object in javascript

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

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

【讨论】:

  • 如果我想根据 parentActivityId 和 id 删除节点,我必须对代码做哪些更改?
  • 我假设,您想删除具有给定parentActivityId 的所有节点,对吧?所以在这种情况下,对于给定的parentActivityId = 2,带有id = 4 的节点将被删除。获取id = 2,运行data.some(findNode); 并应用node.array[node.index].items = [];
  • 我将同时传递 id 和 parentActivityId。基于此,节点应该被删除
  • 但是当您拥有id 时,您将获得不同的节点。然后您可以通过遍历items 属性来选择您想要的parentActivityId
  • 我的最后一个答案具有误导性。您可以使用给定的parentActivityId 选择您想要的节点并使用nodes 属性中的 id 然后选择一个特定的子节点。
【解决方案2】:

您需要在父项数组中找到子节点的索引。应该像循环遍历父项的数组一样简单,直到您点击子 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2015-12-07
    • 2017-12-01
    • 2019-10-26
    相关资源
    最近更新 更多