0

I am looking for a way to do a conditional assignment of value to a key in an object. In my case i have an old data structure in my json file which is different then the new one so for example now the field is seller1FirstName and before it was seller1FName. What i need is a way to assign the value of this field to a var in my code. I know i could check if one exist and then assign it or if not use the other like this

if (data.seller1FirstName) {
   let mySellerFirstName = data.seller1FirstName
 } else {
   let mySellerFirstName = data.seller1FName
 }

i am hoping there is a cleaner and shorter way to do this

SamS87
  • 41
  • 1
  • 6

2 Answers2

3

You could use a ternary 'if' operator to do the same thing in only one line:

let mySellerFirstName = data.seller1FirstName ? data.seller1FirstName : data.seller1FName;
Dharman
  • 30,962
  • 25
  • 85
  • 135
ajzbrun
  • 113
  • 1
  • 12
0

You can use the optional chaining operator in addition to the nullish coalescing operator.

let data = {
  seller1FName : 'value'
}

let newValue = data?.seller1FirstName ?? data.seller1FName;

console.log(newValue);
jateen
  • 642
  • 3
  • 13
  • 1
    This is not strictly the same. `??` will use the second value if the first is `undefined` or `null`. The `if` check in the original would use the second value if the first is falsey (`undefined`, `null`, or `""`). – crashmstr Sep 21 '21 at 16:39