How to remove objects from a JSON object?

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?

+4
source share
2 answers

Hope this helps someone else deal with this. Thanks guys for the help.

Here is the answer and function that I have for me. It is abstract enough to hope to help someone else.

If you pass this function any pair of key values ​​that you want to delete and the parsed JSON object, it will delete it and return true if the element 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; } } } } 
+2
source

Source: https://habr.com/ru/post/1483873/


All Articles