I have an array of objects:
const arr = [
{
name: 'John',
money: 45
},
{
name: 'Lui',
money: 65
},
{
name: 'Kegan',
money: 100
},
... isNewUser ? {
name: 'Eric',
money: 90
} : {}
]
I need to conditionally add the object when it is declared not using array.push. I've tried using the && operator but I just got errors.isNewUser is a boolean variable and if true, array should have 4 items, else the array should only have 3 which doesn't include the newUser object
You can only spread an array into an array. So simply make your conditional element an array.
var arr = [{
name: 'John',
money: 45
},
{
name: 'Lui',
money: 65
},
{
name: 'Kegan',
money: 100
},
...isNewUser ? [{
name: 'Eric',
money: 90
}] : []
]
Anyways, array.push still looks like a better option here!
I like Ajith Gopi's answer very much.
I would additionally use some helper functions.
function toArray(obj) {
if (obj == null) {
return []
}
else if (Array.isArray(obj)) {
return obj
}
else {
return [obj]
}
}
function iif(condition, trueObj, falseObj) {
return condition ? toArray(trueObj) : toArray(falseObj)
}
var arr = [
{
name: 'John',
money: 45
},
{
name: 'Lui',
money: 65
},
{
name: 'Kegan',
money: 100
},
...iif(isNewUser, {
name: 'Eric',
money: 90
})
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With