marcos marcos - 4 months ago 14
Javascript Question

Delete all children in objects array



var arr = [{
"id": "1",
"name": "News",
}, {
"id": "3",
"parent": "1",
"name": "News 2"
}, {
"id": "5",
"parent": "3",
"name": "News",
}, {
"id": "7",
"parent": "5",
"name": "News 2"
}, {
"id": "15",
"name": "News 2"
}, {
"id": "20",
"name": "News 2"
}];

var deleted_id = 1;

for (var i = 0; i < arr.length; i++) {
if (arr[i].parent == deleted_id) {
arr.splice(i, 1);
} else continue;
}





I need to delete item (e.g. With id: "1"). Also I need to delete all levels children, who has "parent" field the same as id of deleted item.

Pay attention that item with id: 3 - is parent for item with id: 5, and item with id: 5 is parent for item with id: 7. They all - should be deleted as well.

There are some deep levels, therefore, result should be:



[{
"id": "15",
"name": "News 2"
}, {
"id": "20",
"name": "News 2"
}]




Answer

First you should find the hierarchy relation. then according to id you want to delete go for it's children and delete them with parent.

var arr = [{"id": "1", "name": "News", }, {"id": "3", "parent": "1", "name": "News 2"}, {"id": "5", "parent": "3", "name": "News", }, {"id": "7", "parent": "5", "name": "News 2"}, {"id": "15", "name": "News 2"}, {"id": "20", "name": "News 2"}];

console.clear();

var children = {};
arr.forEach(function (item) {
	if (item.parent)
		children[item.parent] = (children[item.parent] || []).concat(item.id);
});
function deleteItem(id) {
	if (children[id])
		children[id].forEach(deleteItem)
	var index = arr.findIndex(i => i.id === id);
	if (index >= 0)
		arr.splice(index, 1);
}

deleteItem('1')
console.log(arr);

Comments