Dawid Zbiński Dawid Zbiński - 22 days ago 7
TypeScript Question

Add property to object when it's not null

I want to update my data with patch method without using bunch of IF statements. I want to simply check if anything changed and if yes, put the data into the object and send them out. So far I've got this (code below), now I'm thinking how to add only the NOT NULL variables to the object.

update() {
let address = this.address.split(", ").join(",").split(",").join(" ").split(" ");
let name = this.name.split(" ");

let first = name[0] != this.user['firstName'] ? name[0] : null;
let second = name[1] != this.user['lastName'] ? name[1] : null;
let city = address[0] != this.user['address']['city'] ? address[0] : null;
let state = address[1] != this.user['address']['state'] ? address[1] : null;
let zip = address[2] != this.user['address']['zip'] ? address[2] : null;

let data: IPatchProfile = {
// something like --> property != null ? property: property.value : nothing
}
}


I try to do this simply because I don't want to send out the NULL properties, as it would change other properties to NULL. I'm using this solution because there will be more data to send and I don't want to actually write the IF statements for each (And it was the first solution that came into my mind, maybe there is some better way to do that).

Answer

You could use Object.assign:

let data = Object.assign({},
  first === null ? null || {first},
  ...
);

This works because Object.assign will skip over null parameters.

If you are sure that the property value is not going to be "falsy", then it would be bit shorter to write:

let data = Object.assign({},
  first && {first},
  ...
);

Assuming the object is going to be stringified at some point, since stringification ignores undefined values, you could also try

let data = {
  first: first === null ? undefined : first,
  ...
}