Remove a JSON attribute

JavascriptJson

Javascript Problem Overview


if I have a JSON object say:

var myObj = {'test' : {'key1' : 'value', 'key2': 'value'}}

can I remove 'key1' so it becomes:

{'test' : {'key2': 'value'}}

Javascript Solutions


Solution 1 - Javascript

Simple:

delete myObj.test.key1;

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiong00se0neView Question on Stackoverflow
Solution 1 - JavascriptJosef PflegerView Answer on Stackoverflow
Solution 2 - JavascriptpraneetlokeView Answer on Stackoverflow