javascriptjsonrecursion

Remove parent object of a JSON if it has certain property


I'm getting a JSON structure from an API, that I want to change in my front end. The frontend adds a property to the JSON structure, "isHidden". When I send the modified JSON back, I don't want the object that has "isHidden" to be sent back to the API, but I will still save that internally in my own mongodb.

However, doing this was apparently a bit harder then I thought. I made this function which works but I think is very ugly:

function removeHiddenObject(data,parent){
    for(var property in data){
        if(data.hasOwnProperty(property)){
            if(property == "isHidden" && data[property] === true){
                parent.splice(parent.indexOf(data), 1);
            }
            else {
                if(typeof data[property] === "object") {
                    removeHiddenObject(data[property], data);
                }
            }
        }
    }
    return data;
}

It's a recursive method, but I find it way to complex and weird. Is there a way of simplifying my task?

Here is a jsfiddle for you if you'd like to help out: https://jsfiddle.net/vn4vbne8/


Solution

  • use this code to remove it from json string :

    myJson=s.replace(/,*\s*"[^"]"\s*\:\s*{(.*?)"isHidden"\:([^}]*)}/gm,"");
    

    Be careful in Regex every character is important so use exactly above code. It removes every property that have an object that one of its properties is isHidden.