如何递归删除包含空数组的嵌套对象?

sha*_*un5 4 javascript recursion jquery

我最初收到一个AJAX响应{"B":{"1":"100","3":{"AA":256}},"A":100}并转换为javascript对象:

var jsonOBJ = {};
jsonOBJ = jQuery.parseJSON(data);
Run Code Online (Sandbox Code Playgroud)

未来的响应可以是初始响应的子集或超集.如果服务器上的表值未更改,则停滞数据将替换为空数组.例:

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

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

每次收到AJAX响应时,对象都会更新为:

jQuery.extend(true, jsonOBJ, jQuery.parseJSON(data));
Run Code Online (Sandbox Code Playgroud)

但是我需要javascript对象来保持未更改的部分,所以我需要最终得到一个与上面的示例响应相同的对象:

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

我首选的选项是从转换​​后的响应中删除空对象.是否存在可以执行此操作的jQuery扩展函数的现有函数或修改?

jfr*_*d00 6

您可以使用此代码删除响应中使用空数组的元素.

它循环通过顶层,寻找任何空数组并删除它们.它找到的任何对象,它都会递归到它们中去除空数组:

// 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);
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到它的工作:http://jsfiddle.net/jfriend00/U6qMH/