TypeScript-从JSON删除空值

时间:2018-12-10 16:30:52

标签: json angular typescript

我在服务中有一种方法可以在服务器中保存日期,当此方法将日期发送到服务器时,它会在json中发送与null相同的字段,如何删除具有null值的字段?

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)));
}

json发送到服务器:

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

我要发送的json:

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

1 个答案:

答案 0 :(得分:3)

您可以遍历JSON并删除值是null还是Object.keys(o).length === 0

以下是代码。

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;
}

供参考,添加了stackblitz代码。