0

I need to remove the null values of JSON object before requesting a post. My below code doesn't work, could you please let me know where I'm going wrong?

publish() {
    let resource = JSON.stringify(this.form.value)
        const removeEmpty = (obj) => {
      Object.keys(obj).forEach(key => {
         if (obj[key] && typeof obj[key] === "object") {
           removeEmpty(obj[key]);
         } else if (obj[key] === null) {
           delete obj[key];
         }
       });
       return obj;
    };
    console.log("new obj :" + removeEmpty(resource));
}

Stackblitz for sample

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
  • You can check https://stackoverflow.com/questions/23774231/how-do-i-remove-all-null-and-empty-string-values-from-an-object – Lukas Horak Oct 04 '20 at 08:10

1 Answers1

0

Your resource is a string, since you stringify your object. Please remove the stringify.

publish() {
    let resource = this.form.value;
        const removeEmpty = (obj) => {
      Object.keys(obj).forEach(key => {
         if (obj[key] && typeof obj[key] === "object") {
           removeEmpty(obj[key]);
         } else if (obj[key] === null) {
           delete obj[key];
         }
       });
       return obj;
    };
    console.log("new obj :", removeEmpty(resource));
}
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43