我在obj中获得了很多对象。就像这个
Object {MAILING ADDRESS: "P O BOX 59", APN: "066-102-11-1"}
Object {MAILING ADDRESS: "", APN: ""}
Object {MAILING ADDRESS: "P O BOX 3", APN: "066-105-11-1"}
Object {MAILING ADDRESS: "", APN: ""}
当我对它的Null值应用删除函数时,我得到了这个
Object {MAILING ADDRESS: "P O BOX 59", APN: "066-102-11-1"}
Object {}
Object {MAILING ADDRESS: "P O BOX 3", APN: "066-105-11-1"}
Object {}
我想完全删除对象{}并且只想获得2个具有值的对象。 我删除此值的代码是
(function filter(obj_field) {
$.each(obj_field, function(key, value) {
if (value === "" || value === null) {
delete obj_field.key;
} else if (Object.prototype.toString.call(value) === '[object Object]') {
filter(value);
} else if ($.isArray(value)) {
$.each(value, function(k, v) {
filter(v);
});
}
});
})(obj_field);

答案 0 :(得分:0)
(function filter(obj_field) {
$.each(obj_field, function(key, value) {
if(isEmpty(value)) {
delete obj_field.key;
} else if (Object.prototype.toString.call(value) === '[object Object]')
{
filter(value);
} else if ($.isArray(value)) {
$.each(value, function(k, v) {
filter(v);
});
}
});
})(obj_field);
function isEmpty(obj) {
for(var key in obj) {
if(obj.hasOwnProperty(key))
return false;
}
return true;
}
答案 1 :(得分:0)
使用delete
运算符仅删除引用,它不会删除对象本身。
var myObj = {}
myObj.x = 30;
console.log(myObj.x); // '30'
delete myObj; // It will not delete the object
console.log(myObj.x); // '30'
delete myObj.x; // it will delete the property of the object
console.log(myObj.x); // 'undefined'
答案 2 :(得分:0)
让我们整理一下:
mainObj={
Object1: {"MAILING ADDRESS": "P O BOX 59", APN: "066-102-11-1"},
Object2: {"MAILING ADDRESS": "", APN: ""},
Object3: {"MAILING ADDRESS": "P O BOX 3", APN: "066-105-11-1"},
Object4: {"MAILING ADDRESS": "", APN: ""}
};
for(key in mainObj){
if(!Object.values(mainObj[key]).some(el=>el)){
delete mainObj[key];
}
}
这将创建:
mainObj={
Object1,Object3
};
http://jsbin.com/qazepupupi/edit?console
注意:这个ES6,如果此代码在旧的客户端浏览器上运行,您可以使用下面的代码:
for(key in mainObj){
if(!Object.keys(mainObj[key]).some(function(inlinekey){ return mainObj[key][inlinekey]})){
delete mainObj[key];
}
}