How do you set a variable as the prop of an object?
Consider the below code -
|
|
If we have a dynamic prop for earth
, we can do -
|
|
To define a new, dynamic prop -
- First we define the variable -
lifeExists
- We then use that variable value as a prop and set the prop value
earth[lifeExists] = true
. Note that we cannot useearth.lifeExists = ...
since we are not interested inlifeExists
as a string literal, but only in its value (life
)
So, why use a dynamic prop? Because props may be set within our code or from the data retrieved from database. Javascript by itself will not be aware of all possible props for our object.
We can simplify this further and use the variable within object initialization.
|
|
Again, note that we cannot simply use const earth = { ... , lifeExists: true };
since we do not want to have a prop called lifeExists
. We want a prop called life
which is the value of the variable lifeExists
.