1

I have an array cars of objects. I want to insert the object with header: AUDI only if audi is true.

var audi = false;
var cars= [
   {header: 'fiat',accessor: row},
   {header: 'audi',accessor: row},
   {header: 'bmw',accessor: row}
]

I tried with ternary operator but cars doesn't accept empty object {}. So is there a way to simulate what we usually do for conditional rendering? (ex: audi &&{...} ) THANKS <3

var audi = false;
var cars= [
   {header: 'fiat',accessor: row},
   audi?{header: 'audi',accessor: row}:{},
   {header: 'bmw',accessor: row}
]

1 Answer 1

3

You could use the filter method:

var audi = false;
var cars= [
   {header: 'fiat',accessor: row},
   {header: 'audi',accessor: row},
   {header: 'bmw',accessor: row}
].filter(car => audi || car.header !== 'audi')

Or spread operator:

var audi = false;
var cars= [
   {header: 'fiat',accessor: row},
   ...(audi ? [
      {header: 'audi',accessor: row}
   ] : []),
   {header: 'bmw',accessor: row}
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.