1

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?

6
  • what is the possible depth of your structure? is it indefinite? Are you trying to implement tree-like structure Commented Jul 12, 2016 at 8:16
  • 2
    There's no such thing as a "JSON Object" Commented Jul 12, 2016 at 8:17
  • @Rouz the depth is unknow but it's not infinite. Commented Jul 12, 2016 at 8:24
  • @Sunson So can there be elements on the same level? If you remove one node, what should happen with children nodes? Commented Jul 12, 2016 at 8:26
  • @Rouz If I remove one node, only because it has no children nodes, that is, the array is empty. The example is already given in the question Commented Jul 12, 2016 at 8:31

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.