打字稿模型到json - 忽略空值属性

时间:2018-05-30 22:59:14

标签: jquery json angular typescript

在angular 4 App中, 我的打字稿模型,

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,那么当用户没有输入lastname的值时。我的json输出如下所示,

 {'fname': 'xyz', 'lname': null}

预期结果:

但我想删除json中的所有null值属性。所以我期待

 {'fname':'xyz'}

但是当用户在lname输入值时。 json应该在下面

{'fname':'xyx', 'lname': 'abc'}

如何从打字稿模型

生成此json结果

1 个答案:

答案 0 :(得分: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');
}