user2402616
user2402616

Reputation: 1563

Conditionally assign multiple keys to Object

I have multiple properties that can be assigned to an Object depending on the same conditional

const condition = some boolean;
const foo = [

                bar.fizz,
                bar.fuzz,
                bar.fat,
                condition ? bar.arr[index].bat : '',
                condition ? bar.arr[index].bot : '',               
           ];

Is there any way I can conditionally assign those last two in the ternary (because they rely on the same conditional)?

I know of

 ...(conditional ? [
               bar.arr[index].bat,
               bar.arr[index].bot
     ] 
            : []),

But the only problem with that is that if the conditional is false...then those indices won't exist in the final object. I'll need them to default to empty strings.

I think

...(conditional ? [
                   bar.arr[index].bat,
                   bar.arr[index].bot
         ] 
                : ['', '']),

would work? Anyone see anything wrong with that or is there a better way?

Upvotes: 2

Views: 413

Answers (2)

StepUp
StepUp

Reputation: 38134

Maybe it is a little bit clumsy, but give a try:

condition : bar.arr[index].bot ? bar.arr[index].bot 
    : bar.arr[index].bat ? bar.arr[index].bat 
        : ''

Upvotes: 2

Zirc
Zirc

Reputation: 470

To be honest, the first one is very readable to me. If you are just going to do it for two indices.

In the case that you are dealing with more than two. The third one is great

...(conditional ? [
               bar.arr[index].bat,
               bar.arr[index].bot
     ] 
            : ['', '']),

even better if you just create an array of the same size as your intention, and fill it with empty string such as

...(conditional ? [
               bar.arr[index].bat,
               bar.arr[index].bot
     ] 
            : Array(PUT SIZE OF ARRAY YOU WANT HERE).fill("")),

Upvotes: 2

Related Questions