Deleting JS Object Properties a few levels deep

瘦欲@ 提交于 2019-12-10 10:43:39

问题


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 be able to do is say

delete myObj.first.sub.level

But I won't know what is being passed, or how many levels deep I need to go in order to remove the correct property, meaning it could simply be:

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

Or something more complex:

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 where I have the key "level3" and it's property "Something", but I can't figure out how to back-step correctly in order to delete the full section of that object.

I need to replicate it's place in myObj so I can delete the full passed object.

'myObj.first.sub.level3'

If that makes sense...


回答1:


It's not pretty, but you could 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 a good idea to modify it to test for typeof context[targets[0]] !== 'undefined' before descending. How exactly you react to that (return false, throw, or whatever else) would depend on how you're using it.



来源:https://stackoverflow.com/questions/5059951/deleting-js-object-properties-a-few-levels-deep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!