Aym*_*ari 0 json typescript angular
我的服务中有一种方法可以在我的服务器中保存日期,当此方法将日期发送到服务器时,它会发送与 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)));
}
Run Code Online (Sandbox Code Playgroud)
json 发送到服务器:
{
"name": "test",
"professionType":{
"id": null
},
"comment": null,
"organizationSpecialities":[
{
"speciality":{
"id": null
},
"effective": 2,
"effectiveDate":{
"startDate": null,
"endDate": "2019/12/01"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想发送的json:
{
"name": "test",
"organizationSpecialities":[
"effective": 2,
"effectiveDate":{
"endDate": "2019/12/01"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
您可以遍历 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;
}
Run Code Online (Sandbox Code Playgroud)
作为参考,添加了stackblitz代码。