Reputation: 1295
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?
Upvotes: 5
Views: 7276
Reputation: 1295
Hopefully this helps someone else from struggling with this. Thanks guys for the help.
Here is the answer and the function that I have that works for me. It is abstract enough to hopefully help someone else out.
If you pass this function any key value pair you want to delete and the parsed JSON object it will delete it and return true if the item was found and deleted.
function remove(delKey, delVal, o) {
for (var key in o) {
if (typeof o[key] === "object") {
if (remove(delKey, delVal, o[key])) { return true; }
} else {
if (delKey == key && delVal == o[key]) {
delete o[key];
return true;
}
}
}
}
Upvotes: 2
Reputation: 2807
You can use the delete
operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
Upvotes: 4