大家好我在我的项目中使用模型驱动的表单在我的formGroupObj.value中获取null值。我想删除具有空值的字段。
我目前的输出是这样的。
{
"firstName":"Jack",
"lastName":"M",
"age":null
}
我期待的输出是
{
"firstName":"Jack",
"lastName":"M"
}
有没有任何默认的方式来解决这个问题?
任何人请帮帮我。
答案 0 :(得分:1)
var myObj = {
"firstName":"Jack",
"lastName":"M",
"age":null,
"someotherval": null
};
for(key in myObj) {
if(myObj[key] === null) {
delete myObj[key];
}
}
console.log(myObj);
答案 1 :(得分:0)
var myObj = {
"firstName":"Jack",
"lastName":"M",
"age":null,
"someotherval": null
};
Object.keys(myObj).forEach((key) => (myObj[key] == null) && delete myObj[key]);
console.log(myObj);

答案 2 :(得分:0)
对于嵌套对象(嵌套表单组),我们需要使用递归函数:
const myObj = {
"name": {
"firstName":"Jack",
"lastName": null,
},
"age":null,
"someotherval": "foo"
};
const removeEmpty = (obj) => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === "object") {
// recursive
removeEmpty(obj[key]);
} else if (obj[key] === null) {
delete obj[key];
}
});
};
removeEmpty(myObj);
输出:
const myObj = {
"name": {
"firstName":"Jack",
},
"someotherval": "foo"
};