0

I have an object that looks like this when I do a stringify():

{"key-1":{"inner_key_obj-1":{"A":"1", "AA":"11", "AAA":"111"}, "inner_key_obj-2":{"B":"2", "BB":"22", "BBB":"222"}, "inner_key_obj-3":{"C":"3", "CC":"33", "CCC":"333"}}, "key-2" : "not-an-object-property" }

I'd like to search for and remove they key inner_key_obj-2 so that the object becomes:

{"key-1":{"inner_key_obj-1":{"A":"1", "AA":"11", "AAA":"111"},  "inner_key_obj-3":{"C":"3", "CC":"33", "CCC":"333"}}, "key-2" : "not-an-object-property" }

I know I can use delete to remove a key and its value from an object, but how do I loop thru this to get there?

I did some basic tests such as this:

  for (var key in object) 
        {
            if (object.hasOwnProperty(key)) 
            {                
                //Now, object[key] is the current value
                if (object[key] == null)
                { 
                    delete object[type];
                }
            }
        }

...but to no avail. Can someone explain how to loop thru this?

4
  • 1
    Why would you need to iterate? Do you need to delete the sub-object with key inner_key_obj-2 only in key1, or in any object at the higher level? Commented Dec 15, 2015 at 0:22
  • @jcaron I am looking to delete a key at that specific position. Basically, the first property in this object (key-1) is an array of objects. I need to remove one object out of that array. Commented Dec 15, 2015 at 0:24
  • Is the object that holds the property always on the root object under the property key-1? Or you'd need to search for the object that holds inner_key_obj-2 first? Commented Dec 15, 2015 at 0:29
  • it is always under the root, yes @MinusFour Commented Dec 15, 2015 at 0:30

2 Answers 2

2

Doesn't

delete object["key-1"]["inner_key_obj-2"];

do what you want?

Sign up to request clarification or add additional context in comments.

1 Comment

Why yes, yes it does! I really overthought that one. I am used to doing this stuff in php and in mind was thinking from a whole different viewpoint. Thanks! Will mark correct.
0

I'd just make a new object

var newObject = {};
for(key in object['key-1']){
    if(key != 'inner_key_obj-2'){
        newObject['key-1'][key] = object[key-1][key];
    }
}

Or

delete object["key-1"]["inner_key_obj-2"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.