Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ternary operator while pushing elements into the array

I am trying to add the objects into the array based on the condition.

My expectation is to add two objects when the condition met but I am getting only the last object getting added (its element is missing).

const country = ‘USA’

citizenArray.push([
          {
            label: ‘Alex’,
            value: ’32’,
          },
          country === ‘USA’
            ? ({
                label: ‘John’,
                value: ’28’,
              },
              {
                label: ‘Miller’,
                value: ’40’,
              })
            : {
                label: ‘Marsh’,
                value: ’31’,
              },
        ]);

The output I am getting:

[{
            label: ‘Alex’,
            value: ’32’,
          },
{
                label: ‘Miller’,
                value: ’40’,
              }]

Expected:

[{
            label: ‘Alex’,
            value: ’32’,
          },
{
                label: ‘John’,
                value: ’28’,
              },
{
                label: ‘Miller’,
                value: ’40’,
              }]

Could somebody help me point out where I am doing wrong?

Thanks.

like image 610
brig Avatar asked Feb 05 '26 21:02

brig


2 Answers

How about using the Spread ... operator

const myArray = [
  ...(condition1 ? [item1] : []),
  ...(condition2 ? [item2] : []),
  ...(condition3 ? [item3] : []),
];
like image 83
Gil Epshtain Avatar answered Feb 07 '26 09:02

Gil Epshtain


In Javascript when you placed comma-separated expressions within parathesis it will execute each(left to right) and will return the result of last.

In your case ({ label: 'John', value: '28',}, { label: 'Miller', value: '40',}) results just the last object { label: ‘Miller’, value: ’40’, } and adds to the array.

To make it work to use an array and then use spread syntax to add them.

const country = 'USA';
const citizenArray = [];
citizenArray.push([{
    label: 'Alex',
    value: '32',
  },
  ...(country === 'USA' ? [{
    label: 'John',
    value: '28',
  }, {
    label: 'Miller',
    value: '40',
  }] : [{
    label: 'Marsh',
    value: '31',
  }])
]);

console.log(citizenArray);
like image 36
Pranav C Balan Avatar answered Feb 07 '26 09:02

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!