Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a JSON attribute [duplicate]

if I have a JSON object say:

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

can I remove 'key1' so it becomes:

{'test' : {'key2': 'value'}} 
like image 204
g00se0ne Avatar asked Aug 02 '09 19:08

g00se0ne


People also ask

How do I get rid of duplicate elements?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

Can JSON have duplicate fields?

We can have duplicate keys in a JSON object, and it would still be valid.

How remove duplicates from Jsonarray in Java?

You will need to convert the JSON to Java Objects and then perform the duplicate removal operation. Added code snippet for each of the steps. Hope this helps! You will need to convert the JSON to Java Objects and then perform the duplicate removal operation.

How do I remove duplicates in node JS?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.


2 Answers

Simple:

delete myObj.test.key1; 
like image 153
Josef Pfleger Avatar answered Sep 27 '22 21:09

Josef Pfleger


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.

like image 31
praneetloke Avatar answered Sep 27 '22 20:09

praneetloke