Removing properties of a JS object at several levels

I have an object like this:

var myObj = { first: { sub: { level: "some text", level2: "some more text" }, sub2: { level3: "Something" } }, second: { stuff: "More stuff...lots of stuff" } } 

what i want to do is say

 delete myObj.first.sub.level 

But I will not know what is being transmitted, or how many levels I need in order to remove the correct property, that is, simply:

 Storage.removeItem('myObj.first'); // This is currently working 

Or something more complicated:

 Storage.removeItem('myObj.first.sub2.level3'); // This doesn't work because I'm more than 1 level into the object. 

I’m kind of stuck, because I can get to the point that I have the key "level3", and this is the property "Something", but I can’t figure out how to correctly perform the reverse step to delete the full section of this object.

I need to replicate it to myObj so that I can delete the complete traversed object.

 'myObj.first.sub.level3' 

If that makes sense ...

+1
source share
1 answer

This is not very, but you can use something like this:

 function deepDelete(target, context) { // Assume global scope if none provided. context = context || window; var targets = target.split('.'); if (targets.length > 1) deepDelete(targets.slice(1).join('.'), context[targets[0]]); else delete context[target]; } deepDelete('first.sub.level3', myObj); deepDelete('myObj.first.sub2.level3'); 

It would probably be nice to change it to check for typeof context[targets[0]] !== 'undefined' before the descent. How exactly you react to this (return false, throw or something else) will depend on how you use it.

+7
source

Source: https://habr.com/ru/post/1268441/


All Articles