I have the following code to get a key for a given object. So for the object {"hello": {"data": {"a": "world", "b": "random"}}}
if the key passed in was hello.data.a
, the output would be world
.
(object, key) => {
const keyParts = key.split(".");
let returnValue = object;
keyParts.forEach((part) => {
if (returnValue) {
returnValue = returnValue[part];
}
});
return returnValue;
}
I'm trying to figure out how I can delete a property dynamically in the same fashion. So for example for the same object and key, it would mutate the object to be {"hello": {"data": {"b": "random"}}}
.
Basically I want the same behavior as delete object.hello.data.a
. But the problem is the hello.data.a
part is a dynamic string passed in. Of course something like delete object[key]
wouldn't work since the key has nested levels. It would work if it is only 1 level deep, but wouldn't work for nested items.
One other important note is that performance is extremely important in this case. So although creating a new object and copying over all the properties except for the one I want to delete might work, but I have severe concerns of the performance impact of that vs the delete
keyword.
Due to other external factors I also do not want to set the property value to null
or undefined
. I want the key to actually be removed from the object.
How can I achieve this?