Sunson Sunson - 1 year ago 87
JSON Question

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:


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

function removeEmptyArray(cJSON){
return cJSON;

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


the expect result is
, the code works fine.

but when I have this obj:


The output is

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?

Answer Source

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] }] };


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download