Today I Learned - Rocky Kev

TIL adding properties conditionally using the spread syntax

POSTED ON:

TAGS:

You can conditionally add properties to objects!


const givePerks = true;

const wizard = {
health: 20
spells: 'fireball',
... (givePerks && { perks: 'immune to fire' }),
}

if givePerks === false then the other object never gets added.


Related TILs

Tagged:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL a neat way to clone and object and override the items

Spread the object into a new object, then override the element later.

TIL You can dynamically name objects

Not all Object keys have to be hard-coded strings. To make it dynamic, use [brackets].