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}
]
CodePudding user response:
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}
]