I've been breaking my head for hours to find out how I can delete objects recursively in multidimensional array based on key value. I need to delete all objects containing exclude: true in the example array below. I tried looping the items with a recursion function but I'm struggeling with splicing the items out of the array...
// example multidimensional array with objects
let array: Object[] = [
// exclude on level 1
{
name: 'A',
exclude: true,
content: [
{
name: 'A-A',
},
{
name: 'A-B',
exclude: true,
},
{
name: 'A-C',
content: [
{
name: 'A-C-A',
}
]
}
]
},
// exclude on level 2
{
name: 'A',
content: [
{
name: 'A-A',
},
{
name: 'A-B',
exclude: true,
},
{
name: 'A-C',
content: [
{
name: 'A-C-A',
}
]
}
]
},
// exclude on level 2 and 3
{
name: 'A',
content: [
{
name: 'A-A',
},
{
name: 'A-B',
exclude: true,
},
{
name: 'A-C',
content: [
{
name: 'A-C-A',
exclude: true,
}
]
}
]
}
]
// run function
deleteItems(array);
// path is an array containing the indexes of the items
// e.g. path = [0, 0, 0] --> array[0][0][0]
function deleteItems(arr, path_index: number = 0, path: any[] = [0]): void {
// loop through arr
for (let i = 0; i < arr.length; i++) {
// get item
let item = arr[i];
// set path
path[path_index] = i;
// delete here somehow the item with corresponding path
if (item['exclude']) {
console.log('path', path);
}
// recursion
if ('content' in item) {
// +2 to path index (1. for content, 2. for i)
let path_index_ref = path_index + 2;
// create new path so old path does not get changed
let path_ref = path.slice();
path_ref.push('content');
this.deleteFlowchartItem(item['content'], path_index_ref, path_ref);
} // if content
} // for
} // deleteFlowchartItem()