Ajmal Sha
Ajmal Sha

Reputation: 956

Removing all null value fields on form submit in angular 2

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

Answers (4)

Ben Racicot
Ben Racicot

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

andreivictor
andreivictor

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

Sajeetharan
Sajeetharan

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

mehulmpt
mehulmpt

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

Related Questions