Если путь всегда будет состоять из 3 (или менее) индексов, вы можете легко сделать это следующим образом:
function deleteByPath(arr, path) {
const index = path.split('-').map((x) => +x);
if ( index.length < 1) {
return null;
} else if ( 1 === index.length ) {
return arr.splice(index[0], 1);
} else if ( 2 === index.length ) {
return arr[index[0]].child.splice(index[1], 1);
} else {
return arr[index[0]].child[index[1]].child.splice(index[2], 1);
}
}
const arr = [
{
name: 'FolderA',
child: [
{
name: 'FolderB',
child: [
{
name: 'FolderC0',
child: [],
},
{
name: 'FolderC1',
child: [],
},
],
},
],
},
{
name: 'FolderM',
child: [],
},
];
console.log(deleteByPath(arr, "0-0-1"));
console.log(deleteByPath(arr, "0-1"));
console.log(deleteByPath(arr, "0"));
Если путь будет состоять, возможно, из менее чем 3 частей, вы можете настроить функцию deleteByPath
для обработки случаев на основе количества частей.
если путь будет произвольным и может иметь любую длину, вы можете настроить функцию deleteByPath
на рекурсивную, как показано ниже:
function deleteByIndexRecursive(arr, index, current) {
return current+1 < index.length ? deleteByIndexRecursive(arr.child[index[current]], current+1) : arr.child.splice(index[current], 1);
}
function deleteByPath(arr, path) {
const index = path.split('-').map((x) => +x);
if ( 1>index.length) {
return null;
} else if ( 1===index.length) {
return arr.splice(index[0], 1);
} else {
return deleteByIndexRecursive(arr[index[0]], index, 1);
}
}