Aymen Kanzari
Aymen Kanzari

Reputation: 2013

Typescript - remove null values from json

i have a method in my service to save a date in my server, when this method sends the date to the server, it sends same fields as null in the json, how can i remove the fields with null value?

public create<T>(post: any): Observable<T> {
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };
    return this.httpClient
        .post<T>(`${this.url}`, JSON.stringify(post), httpOptions)
        .pipe(catchError((err, source) => this.responseHandler.onCatch(err, source)));
}

the json send to server:

{
   "name": "test",
   "professionType":{
      "id": null
   },
   "comment": null,
   "organizationSpecialities":[
        {
         "speciality":{
            "id": null
         },
         "effective": 2,
         "effectiveDate":{
            "startDate": null,
            "endDate": "2019/12/01"
         }
      }
   ]
}

the json i want to send:

{
   "name": "test",
   "organizationSpecialities":[
         "effective": 2,
         "effectiveDate":{
            "endDate": "2019/12/01"
         }
      }
   ]
}

Upvotes: 0

Views: 3832

Answers (1)

RANJIT PATRA
RANJIT PATRA

Reputation: 864

You can loop through the JSON and remove if the value is null or Object.keys(o).length === 0.

Following is the code.

cleanData(o) {
  if (Object.prototype.toString.call(o) == "[object Array]") {
    for (let key = 0; key < o.length; key++) {
      this.cleanData(o[key]);
      if(Object.prototype.toString.call(o[key]) == "[object Object]") {
        if(Object.keys(o[key]).length === 0){
          o.splice(key, 1);
          key--;
        }
      }

    }
  }
  else if (Object.prototype.toString.call(o) == "[object Object]") {
    for (let key in o) {
      let value = this.cleanData(o[key]);
      if (value === null) {
        delete o[key];
      }
      if(Object.prototype.toString.call(o[key]) == "[object Object]") {
        if(Object.keys(o[key]).length === 0){
          delete o[key];
        }
      }
      if(Object.prototype.toString.call(o[key]) == "[object Array]") {
        if(o[key].length === 0){
          delete o[key];
        }
      }
    }
  }
  return o;
}

For reference added stackblitz code.

Upvotes: 11

Related Questions