Deleting an object based on the id in javascript

纵饮孤独 提交于 2020-01-06 17:01:11

问题


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

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



回答2:


You need to find the index of the child node in the parents item array. Should be as simple as looping over the items array of the parent until you hit the child id.

Once you have the index of the child node use that as the first parameter in the splice function

See below for a rough example (you will need to add error checking code etc for situations where the parent or child is not found)

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


来源:https://stackoverflow.com/questions/32132222/deleting-an-object-based-on-the-id-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!