How do you recursively delete nested objects containing an empty array?

I first get the AJAX response {"B":{"1":"100","3":{"AA":256}},"A":100} and converted to a javascript object:

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

Future answers may be subsets or supersets of the original answer. If the table value remains unchanged on the server, stagnant data is replaced by an empty array. Example:

{"B":{"1":"90","2":200,"3":[]}}

{"B":[],"A":20}

Each time an AJAX response is received, the object is updated:

 jQuery.extend(true, jsonOBJ, jQuery.parseJSON(data)); 

But I need a javascript object to save the unchanged parts, so I need to end up with an object that will be equivalent to the following with the above example answers:

 jsonOBJ = jQuery.parseJSON('{"B":{"1":"90","2":200,"3":{"AA":256}},"A":20}'); 

My preferred option is to remove empty objects from the converted response. Is there an existing function or modification of the jQuery extension function that would do this?

+3
source share
2 answers

You can remove elements in your answer with an empty array using this code.

It goes through the upper level, looking for any empty arrays and deleting them. Any objects that it finds, it is overwritten to also remove empty arrays in them:

 // make sure the ES5 Array.isArray() method exists if(!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) == '[object Array]'; }; } function removeEmptyArrays(data) { for (var key in data) { var item = data[key]; // see if this item is an array if (Array.isArray(item)) { // see if the array is empty if (item.length == 0) { // remove this item from the parent object delete data[key]; } // if this item is an object, then recurse into it // to remove empty arrays in it too } else if (typeof item == "object") { removeEmptyArrays(item); } } } var jsonOBJ = {}; jsonOBJ = jQuery.parseJSON(data); removeEmptyArrays(jsonOBJ); 

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

+5
source

Not what I requested, but removing empty arrays from a JSON string is a solution:

 jQuery.extend(true, jsonOBJ, jQuery.parseJSON(data.replace(/"[A-Za-z0-9_]*":\[\]/,'').replace(/{,/,'{').replace(/,}/,'}'))); 
0
source

All Articles