如何递归删除包含空数组的嵌套对象? [英] How do you recursively remove nested objects that contain an empty array?
问题描述
我最初收到{"B":{"1":"100","3":{"AA":256}},"A":100}
的AJAX响应,并转换为javascript对象:
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:
{"B":{"1":"90","2":200,"3":[]}}
{"B":[],"A":20}
每次收到AJAX响应时,对象都会更新为:
Everytime an AJAX response is received, the object is updated with:
jQuery.extend(true, jsonOBJ, jQuery.parseJSON(data));
但是我需要javascript对象来保留未更改的部分,因此我需要在上面的示例响应中得到一个等效于以下内容的对象:
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}');
我的首选方法是从转换后的响应中删除空对象.是否有现有功能或对jQuery扩展功能的修改可以做到这一点?
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?
推荐答案
您可以使用此代码删除响应中带有空数组的元素.
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
} else if (typeof item == "object") {
removeEmptyArrays(item);
}
}
}
var jsonOBJ = {};
jsonOBJ = jQuery.parseJSON(data);
removeEmptyArrays(jsonOBJ);
您可以在这里看到它的工作: http://jsfiddle.net/jfriend00/U6qMH/
You can see it work here: http://jsfiddle.net/jfriend00/U6qMH/
这篇关于如何递归删除包含空数组的嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!