I have two Typescript objects x
and y
as defined below:
let x = {A: 1, B: 2};
console.log('x = ', x);
let y = {A: 1};
console.log('y = ', y);
> x = {"A": 1, "B": 2}
> y = {"A": 1}
Now I want to set y.B
to x.B
iff x.B
exists.
And I want to set y.C
to x.C
iff x.C
exists.
Is there an operator I can use to achieve this? Currently I do this, but it seems clunky:
if (x.hasOwnProperty('B') && x.B !== null) {
y.B = x.B;
}
if (x.hasOwnProperty('C') && x.C !== null) {
y.C = x.C;
}
2
Answers
Not exactly sure about what you want to do but maybe this is the case for the Optional Chaining operator (
?.
).It can be used like this:
This operator checks for the existence of that property before accessing it.It accesses thex.C
and evaluates the expression toundefined
if it throws an error (instead of throwing the error).In most cases your code is equivalent of
(except if x prototype has B or if x.B is
undefined
)