Removing id based object in javascript

This is a continuation of Pushing an object into an array , where I clicked an object into an array, defining parentActivityId. Now I wanted to delete the object based on its id. I tried the code below based on the following question, but it doesn't work. Will someone 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); 
+2
javascript arrays for-loop splice
source share
2 answers

This solution offers Array.prototype.some() recursive way with some basic error handling.

Data taken from Unable to push an object into the parent array, specifying the parent identifier of the object in javascript .

A key feature is the callback to find the desired node and 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>'); 
+1
source share

You need to find the index of the node child in the array of parent elements. It should be as simple as looping over an array of parent elements until you hit the child id.

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

See the example below (you 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); 
0
source share

All Articles