Skip to content Skip to sidebar Skip to footer

Deleting An Object Based On The Id In Javascript

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

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

functionfindNode(a, i, o) {
    if (a.id === id) {
        node = { array: o, index: i };
        returntrue;
    }
    returnArray.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>');

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

Post a Comment for "Deleting An Object Based On The Id In Javascript"