Ahelp
Ahelp

Reputation: 313

typescript model to json - Ignore null value property

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

Upvotes: 2

Views: 2901

Answers (2)

Jadranko Krajinović
Jadranko Krajinović

Reputation: 11

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.

Upvotes: 1

CGundlach
CGundlach

Reputation: 671

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

Upvotes: 1

Related Questions