2

In angular 4 App, My typescript Model,

export class Person{
  fname:string,
  lname?:string
}

lname is optional. Fill the model like below in the component

//Query form data
var people = form.get('people');

let model = new Person(){
  fname: people.get('firstname'),
  lname: people.get('lastname')
}

At this scenario, if i try to convert my model to json, when user doesn't enter value for lastname. My json output will look like below,

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

Expected Result:

But I want to eliminate all the null value properties in my json. So I am expecting

 {'fname':'xyz'}

but when user enters value at lname. the json should like below

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

How can i produce this json result from typescript model

2 Answers 2

1

Check the content of the lastname property of your form before inserting the value. Don't insert a value if it's not a string, assuming that's what that property contains.

Like this:

//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');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Simple fix
1

I've created a util lib for that. Maybe it can help. https://www.npmjs.com/package/ngx-super-model

Using clean() function on instance that extends Model class will remove null, undefined and NaN.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.