使用JS或jQuery如何删除键值为“Null
”和""
的键值对。
例如
之前:
Object {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null}
改变:
Object {style: "fruit", origin: "Thailand", day: "18d"}
最佳答案
这有两个部分:
this question's answers涵盖了很多方法来做第一个。假设您只在乎“自己的”(非继承)属性,我可能会使用
Object.keys
来获取属性名称数组,然后对其进行循环。第二个是使用
delete
运算符完成的。所以:
Object.keys(theObject).forEach(function(key) {
var value = theObject[key];
if (value === "" || value === null) {
delete theObject[key];
}
});
现场示例:
var theObject = {
style: "fruit",
origin: "Thailand",
day: "18d",
color: "",
weight: null
};
console.log("Before:", JSON.stringify(theObject, null, 2));
Object.keys(theObject).forEach(function(key) {
var value = theObject[key];
if (value === "" || value === null) {
delete theObject[key];
}
});
console.log("After:", JSON.stringify(theObject, null, 2));
关于javascript - JS或jQuery如何删除键值对,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39314415/