I want to set some keys in object depending on flag value
For example
const ourFlag = true //true or false depends on case
const ourObject = {
name: 'Pablo',
secondName: 'Picasso',
[ourFlag && 'age']: 20,
[ourFlag && 'moreComplexValue']: [
{
val: true
},
{
val: false
}
]
}
As long as ourFlag
is set to true
everything works as I expected, but when I change it's value to false
some weird things started to come.
property age
is no longer present - good
but property moreComplexValue
is now false
Code I get when flag is false
:
{
name: 'Pablo',
secondName: 'Picasso',
// age disappear as I expected
false: [ //why!?!
{
val: true
},
{
val: false
}
]
}
Code I get when flag is true
:
{ . //brilliant everything is fine
name: 'Pablo',
secondName: 'Picasso',
age: 20,
moreComplexValue: [
{
val: true
},
{
val: false
}
]
}
It's any way to handle it with that computed properties?
[flag && key]
evaluates to false
or key
, and this is exactly what your literal does, converting false
to a string and overwriting it when the flag is false.
A better option would be to use an object spread ...flag && object
, which will expand to the object in the true case, and to an empty Boolean
in the false case, thus essentially skipping it.
let ourFlag = true
const a = {
name: 'Pablo',
secondName: 'Picasso',
...ourFlag && {age: 20},
...ourFlag && {moreComplexValue: [1, 2, 3]}
}
ourFlag = false
const b = {
name: 'Pablo',
secondName: 'Picasso',
...ourFlag && {age: 20},
...ourFlag && {moreComplexValue: [1, 2, 3]}
}
console.log(a)
console.log(b)