如何过滤像这样的对象:
{"firstname":"foo","lastname":"bar","driving":"","overnight":""}
到
{"firstname":"foo","lastname":"bar"}
仅删除空键/值对
答案 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);