Remove a JSON attribute [duplicate]

Remove a JSON attribute [duplicate]

This question already has an answer here:

How do I remove a property from a JavaScript object?

38 answers

if I have a JSON object say:
var myObj = {‘test’ : {‘key1’ : ‘value’, ‘key2’: ‘value’}}

can I remove ‘key1’ so it becomes:
{‘test’ : {‘key2’: ‘value’}}

Solutions/Answers:

Solution 1:

Simple:

delete myObj.test.key1;

Solution 2:

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.