Dynamically delete object property JavaScript
To delete, .pop()
off the last key to identify the property to remove. If you want to avoid the delete
keyword, you'll also want to replace the last object on which that key is on, rather than mutate it, so .pop()
off the next last key as well.
Then, use your current method (or .reduce
) to access the last outer object. To delete one of its keys:
- To mutate with
delete
, using the saved key, usedelete[nextLastKey][lastKey]
- To create an entirely new object but without the saved key, use rest syntax to exclude that
lastKey
during the creation of a new one, then assign the new object to thenextLastKey
of the parent object:
const fn = (object, key) => {
const keys = key.split(".");
const lastKey = keys.pop();
const nextLastKey = keys.pop();
const nextLastObj = keys.reduce((a, key) => a[key], object);
// delete version:
// delete nextLastObj[nextLastKey][lastKey]
// non-delete version:
const { [lastKey]: _, ...rest } = nextLastObj[nextLastKey];
nextLastObj[nextLastKey] = rest;
return object;
}
const obj = {"hello": {"data": {"a": "world", "b": "random"}}};
const result = fn(obj, 'hello.data.a');
console.log(result);