Take the 2-minute tour ×

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 responses can be subsets or supersets of the initial response. If the value of a table is unchanged at the server, the stagnant data is replaced with an empty array. Example:



Everytime an AJAX response is received, the object is updated with:

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

But I need the javascript object to keep the unchanged portions, so I need to end up with an object that would be equivalent to the following with the example responses above:

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

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

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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

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

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

share|improve this answer
I see your defining it, but when would the method not exist? –  shaun5 Feb 25 '12 at 19:07
@shaun5 - Older browsers do not have Array.isArray() built in so we make sure it's defined even for them without replacing it if it does already exist. –  jfriend00 Feb 25 '12 at 19:29
@shaun5 - Added working jsFiddle: jsfiddle.net/jfriend00/U6qMH –  jfriend00 Feb 25 '12 at 19:54
add comment

Not really what I asked for, but removing the empty arrays from the JSON string is a solution:

jQuery.extend(true, jsonOBJ, jQuery.parseJSON(data.replace(/"[A-Za-z0-9_]*":\[\]/,'').replace(/{,/,'{').replace(/,}/,'}')));
share|improve this answer
add comment

Your Answer


