简体   繁体   中英

Recursively remove object which contains empty array in nest json object

I want to dynamically delete json object which contains empty array. I've found this link similar question here . But it doesn't work for me in my case.

Suppose I have a JSON object:

{"op":"1","parameters":[{"op":"2-1","parameters":[]},{"op":"2-2","parameters":[1,2]}]}

I've wrote a sample code to do the stuff recursively:

function removeEmptyArray(cJSON){
    if(!cJSON)
        return cJSON;

    for(var i=cJSON.parameters.length-1;i>=0;i--){
        if(!(cJSON.parameters[i].parameters instanceof Array))
            continue;
        if(cJSON.parameters[i].parameters.length==0){
            cJSON.parameters.splice(i,1);
        }else{
            cJSON.parameters[i] = removeEmptyArray(cJSON.parameters[i]);
        }
    }
    return cJSON;

}

the expect result is {"op":"1","parameters":[{"op":"2-2","parameters":[1,2]}]} , the code works fine.

but when I have this obj:

{"op":"1","parameters":[{"op":"2-1","parameters":[{"op":"3-1","parameters":[]}]},{"op":"2-2","parameters":[1,2,3]}]}

The output is {"op":"1","parameters":[{"op":"2-1","parameters":[]},{"op":"2-2","parameters":[1,2,3]}]}

Obviously it does not dynamically remove the json obj whose "op" is "2-1".

So how to solve it in an elegant way, using pure javascript?

You could use a breadth first algoritm, which look first in the depth and then deletes, if necessary.

 function isNotEmpty(object) { if (Array.isArray(object.parameters)) { object.parameters = object.parameters.filter(isNotEmpty); return object.parameters.length; } return true; } var object = { "op": "1", "parameters": [{ "op": "2-1", "parameters": [{ "op": "3-1", "parameters": [] }] }, { "op": "2-2", "parameters": [1, 2, 3] }] }; isNotEmpty(object); console.log(object); 

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