简体   繁体   中英

Remove objects/fields which contains a specific word

I have a JSON file; I want to remove all of the fields or objects, whose names are a specific word (lets say "test") and then return the stripped JSON file back; how can I do it in Node.JS?

Here is an example of my JSON file:

{
    "name": "name1",
    "version": "0.0.1",
    "storage": {
        "db": {
            "test": "STRING",
            "tets2": "STRING",

        },
        "test": {
            "test11": "STRING",
            "test2": {
                "test3": "0",
                "test4": "0"
            },
            "test5": {
                "test6": "0",
                "test7": "0"
            }
        },
        "test8": {
            "test9": "STRING",
            "test10": "STRING"
        }
    }
}

The desired output:

{
    "name": "name1",
    "version": "0.0.1",
    "storage": {
        "db": {            
            "tets2": "STRING",
        },        
        "test8": {
            "test9": "STRING",
            "test10": "STRING"
        }
    }
}

I tried the folloiwng, but I dont know how to use typeof() and check if it is an objectgo deeper in the tree! could you please help me in this regard

var new_json = config;

async.each(Object.keys(config), function(key) {

    if (key == "test") {
        delete new_json[key];
    }

    while (typeof (new_json[key]) == "object") {
        // How can I handle it here

    }
});
console.log("done!");

Below Recursion code will work. But you need to list of acceptable fields or not acceptable fields and based on that you need to change the below condition IF you know not acceptable fields then use below conditions.

unAcceptableFields.indexOf(key) > 0



var acceptableFields = ["name","version","storage","db", "test9", "test10","tets2", "test8", "test9", "test10" ];
console.log(removeUnwantedFields(testObject, acceptableFields));

function removeUnwantedFields(jsData,acceptableFields) {
    var key;
    if (jsData) {
        for (key in jsData) {           
            if (acceptableFields.indexOf(key) == -1) {
                delete jsData[key];
            }
            else if(typeof jsData[key] === "object"){
              jsData[key] = removeUnwantedFields(jsData[key],acceptableFields);
            }
        }
    }
    return jsData;
}

Refer this URL http://jsfiddle.net/55x2V/

This function should do it:

function clean(obj,target) {
    var tmpobj = obj;
    for (var key in tmpobj) {
        if (key === target) {
            delete obj[key];
        }
        else if (typeof obj[key] === "object") {
            obj[key] = clean(obj[key],target); 
        }
    }
    return obj;
}

called this way:

json_struct = clean(json_struct,"test")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM