Search code examples
javascriptecmascript-6ecmascript-5

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.


Solution

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