按空属性/条目过滤对象

时间:2016-02-04 09:01:06

标签: javascript object filter

如何过滤像这样的对象:

{"firstname":"foo","lastname":"bar","driving":"","overnight":""}

{"firstname":"foo","lastname":"bar"}

仅删除空键/值对

3 个答案:

答案 0 :(得分:0)

for (key in obj) {
    if (obj.hasOwnProperty(key) && obj[key] === '') {
        delete obj[key];
    }
}

答案 1 :(得分:0)

Object.keys()和Array.prototype.forEach()的解决方案:

var original = {"firstname":"foo","lastname":"bar","driving":"","overnight":""};
var filtered = {}
Object.keys(original).forEach(function(key) {
    if (original[key] !== "") {
        filtered[key] = original[key];
    }
});
console.log(filtered);

答案 2 :(得分:0)

您也可以试试这个。此代码会删除测试驾驶

var obj = {"firstname":"foo","lastname":"bar","driving":"","overnight":"", "test": null};
Object.keys(obj).forEach(function(k) {
    if (!obj[k] || obj[k] === "") {
        delete obj[k];
    }
});
console.log(obj);