I have an object as shown:
const arr = [
{
name: 'FolderA',
child: [
{
name: 'FolderB',
child: [
{
name: 'FolderC0',
child: [],
},
{
name: 'FolderC1',
child: [],
},
],
},
],
},
{
name: 'FolderM',
child: [],
},
];
And I have path as string:
var path = "0-0-1".
I have to delete the object:
{
name: 'FolderC1',
child: [],
},
Which I can do so by doing,
arr[0].child[0].splice(1, 1);
But I want to do it dynamically. Since path string can be anything, I want the above '.' operator and splice definition to be created dynamically to splice at particular place.
The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.
Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.
To remove a property from an object in TypeScript, mark the property as optional on the type and use the delete operator. You can only remove properties that have been marked optional from an object.
You could reduce the indices by saving the last index and returning the children of the actual index. Later splice with the last index.
function deepSplice(array, path) {
var indices = path.split('-'),
last = indices.pop();
indices
.reduce((a, i) => a[i].child, array)
.splice(last, 1);
}
const array = [{ name: 'FolderA', child: [{ name: 'FolderB', child: [{ name: 'FolderC0', child: [] }, { name: 'FolderC1', child: [] }] }] }, { name: 'FolderM', child: [] }];
deepSplice(array, "0-0-1");
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could split your path
and use the parts, like so:
let path = '0-0-1';
let parts = path.split('-');
// Call your splice using your parts (unsure if your '1' is the index, or deleteCount).
// If parts[2] is the index
arr[parts[0]].child[parts[1]].splice(parts[2], 1);
// If parts[2] is the deleteCount:
arr[parts[0]].child[parts[1]].splice(1, parts[2]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With