Skip to content Skip to sidebar Skip to footer

How Do You Recursively Remove Nested Objects That Contain An Empty Array?

I initially receive an AJAX response of {'B':{'1':'100','3':{'AA':256}},'A':100} and converted to a javascript object: var jsonOBJ = {}; jsonOBJ = jQuery.parseJSON(data); Future r

Solution 1:

You can remove the elements in your response with empty arrays with this code.

It cycles through the top level, looking for any empty arrays and removing them. Any objects it finds, it recurses into to also remove empty arrays in them:

// make sure the ES5 Array.isArray() method existsif(!Array.isArray) {
  Array.isArray = function (arg) {
    returnObject.prototype.toString.call(arg) == '[object Array]';
  };
}

functionremoveEmptyArrays(data) {
    for (var key in data) {
        var item = data[key];
        // see if this item is an arrayif (Array.isArray(item)) {
            // see if the array is emptyif (item.length == 0) {
                // remove this item from the parent objectdelete data[key];
            }
        // if this item is an object, then recurse into it // to remove empty arrays in it too
        } elseif (typeof item == "object") {
            removeEmptyArrays(item);
        }
    }    
}

var jsonOBJ = {};
jsonOBJ = jQuery.parseJSON(data);
removeEmptyArrays(jsonOBJ);

You can see it work here: http://jsfiddle.net/jfriend00/U6qMH/

Solution 2:

this will complete the function ;)

removeEmptyArrays(data) {
    for (var key indata) {
        var item = data[key];
        // see if this item is an arrayif (Array.isArray(item)) {
          // see if the array is emptyif (item.length == 0) {
             // remove this item from the parent object
             delete data[key];
           } else {
             this.removeEmptyArrays(item);
           }
        // if this item is an object, then recurse into it // to remove empty arrays in it too
        } elseif (typeof item == "object") {
            this.removeEmptyArrays(item);
        }
    }    
},

Post a Comment for "How Do You Recursively Remove Nested Objects That Contain An Empty Array?"