Reputation: 956
Hi all i'm using a Model driven form in my project on submit i get null value in my formGroupObj.value . I want to remove this fields which having null values .
My current output is look like this.
{
"firstName":"Jack",
"lastName":"M",
"age":null
}
My expecting output is
{
"firstName":"Jack",
"lastName":"M"
}
Is there any default way to get this out put?
Any one please help me.
Upvotes: 5
Views: 5402
Reputation: 5925
I cleaned up andreivictor's answer and extended it to also remove an empty FormGroups.
removeEmpty = (obj: any) => {
Object.keys(obj).forEach((key) => {
// recursive for FormGroups
if (obj[key] && typeof obj[key] === 'object') this.removeEmpty(obj[key]);
// null values
if (obj[key] === null) delete obj[key];
// empty objects - empty FormGroups
if (JSON.stringify(obj[key]) === '{}') delete obj[key];
});
return obj;
};
Upvotes: 0
Reputation: 8461
For nested objects (nested Form Groups), we need to use a recursive function:
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);
Output:
const myObj = {
"name": {
"firstName":"Jack",
},
"someotherval": "foo"
};
Fiddle: https://jsfiddle.net/xndbj3La/
Upvotes: 1
Reputation: 222582
var myObj = {
"firstName":"Jack",
"lastName":"M",
"age":null,
"someotherval": null
};
Object.keys(myObj).forEach((key) => (myObj[key] == null) && delete myObj[key]);
console.log(myObj);
Upvotes: 8
Reputation: 16577
var myObj = {
"firstName":"Jack",
"lastName":"M",
"age":null,
"someotherval": null
};
for(key in myObj) {
if(myObj[key] === null) {
delete myObj[key];
}
}
console.log(myObj);
Upvotes: 2