I am trying to delete an object from a JSON object. Is there an easy way to do it? If I have an object can I delete the item from it, or is it better to convert the object into an array and splice it? What are the pros and cons of each.
The logic I want to write is something 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;
}
}
}
}
changed code to use delete instead of splice
So this is basically what I would like to do, if there is an easier way then please let me know. The problem I am having here is A. I do not know where to splice. B. if I do splice, I think I am not going to return the spliced result through the recursion to the other objects.
My issue is since I will have different JSON every time I do not know the nested properties. That is why I am using the stack variable. Stack will the nested properties. SO if I want to delete say the color of an apple, stack will be json.fruit.apple.color. But it is a string not an object.
Anyways, does anyone have a better solution for deleting an object from JSON?
deleteoperator.deleteoperator. See MDN's docs.