I am trying to remove an object from a JSON object. Is there an easy way to do this? If I have an object, can I remove an element from it or is it better to convert the object to an array and spliced ββit? What are the pros and cons of each.
The logic I want to write is like this.
function remove( delKey, delVal, o, stack){ for(var key in o) { if(typeof o[key] === "object") { stack != undefined ? stack += "." + key : stack = key; remove(delKey, delVal, o[key], stack); } else { if(delKey == key && delVal == o[key]) { delete o; } } } }
modified code to use delete instead of splicing
So this is basically what I would like to do, if there is an easier way, please let me know. The problem I am facing here is A. I do not know where to join. B. If I am doing a splice, I think that I am not going to return the result of splicing through recursion to other objects.
My problem is that I will have different JSON every time I donβt know the attached properties. This is why I use the stack variable. The stack will be nested properties. SO, if I want to remove the Apple color, the stack will be json.fruit.apple.color. But this is a string, not an object.
Anyway, does anyone have a better solution to remove an object from JSON?
source share