Here\'s my code:
Here's how you can do it:
// Will result in { foo: 'foo', bar: 'bar'}
const item = {
foo: 'foo',
... true && { bar: 'bar' },
... false && { falsy: 'falsy' },
}
console.log(item)
Explanations:
Short-circuit evaluation (true && {}
, false && {}
) would return an Object
or a Boolean false
value.
In the case an Object
is returned, its properties get spread and assigned to the parent object.
In the case false
value is returned, the parent object isn't polluted, because ES6 treats false, undefined, null and etc
values as {}
. Therefore spreading ...{}
won't assign any properties to the parent object. More details about this, you can find here.
Here's how you can do it:
db('fl').insert({
nev: nev,
tipus: tipus,
szid: szid,
...tipus === 'hianyos' ? { rang: -1 } : {}
})
Explanations:
As you can see the ternary operator always returns an object.
If the condition is true, then it returns { rang: -1 }
, otherwise an empty object {}
.
After that we spread out ...
the resulted object (from the ternary operation) and the object's properties are assigned to the parent object.
If there aren't any properties, then nothing will be assigned, which is our goal.
Code example: (sometimes few lines of code better than a thousands of words)
// Will result in { foo: 'foo', bar: 'bar'}
const item = {
foo: 'foo',
... true ? { bar: 'bar' } : {},
... false ? { falsy: 'falsy' } : {},
}
console.log(item)
In other answer I explained the same idea, but for arrays. You can check it too here.