jquery - typescript 模型转换为 json - 忽略空值属性
在 Angular 4 应用中,我的 TypeScript 模型,
export class Person{
fname:string,
lname?:string
}
lname 是可选的。在组件中按如下方式填写模型
//Query form data
var people = form.get('people');
let model = new Person(){
fname: people.get('firstname'),
lname: people.get('lastname')
}
在这种情况下,如果我尝试将我的模型转换为 JSON,而用户没有输入姓氏时。我的 JSON 输出将如下所示,
{'fname': 'xyz', 'lname': null}
预期结果:
但我想在我的 JSON 中删除所有空值属性。所以我期待
{'fname':'xyz'}
但是当用户在 lname 输入值时,json 应该如下所示
{'fname':'xyx', 'lname': 'abc'}
我如何从 TypeScript 模型生成这个 JSON 结果
答案#1
在插入值之前,请检查表单的 lastname 属性的内容。如果它不是字符串,不要插入值,假设该属性包含的就是字符串。
像这样:
//Query form data
var people = form.get('people');
const model = new Person();
model.fname = people.get('firstname');
if (typeof people.get('lastname') === 'string') {
model.lname = people.get('lastname');
}
答案#2
我为此创建了一个工具库。也许它能帮上忙。https://www.npmjs.com/package/ngx-super-model
在继承自 Model 类的实例上使用 clean() 函数将删除 null、undefined 和 NaN。
