Search code examples
javascriptarraysfor-loopsplice

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

Solution

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