if I have a JSON object say:
var myObj = {'test' : {'key1' : 'value', 'key2': 'value'}}
can I remove 'key1' so it becomes:
{'test' : {'key2': 'value'}}
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.
We can have duplicate keys in a JSON object, and it would still be valid.
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.
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.
Simple:
delete myObj.test.key1;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With