Home > Enterprise >  How to assign value to var conditionally [duplicate]
How to assign value to var conditionally [duplicate]

Time:09-22

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

CodePudding user response:

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

let mySellerFirstName = data.seller1FirstName ? data.seller1FirstName : data.seller1FName;

CodePudding user response:

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

  • Related