This page looks best with JavaScript enabled

Use variable value for object prop

 ·   ·  ☕ 2 min read

How do you set a variable as the prop of an object?

Consider the below code -

1
const earth = { name: "earth" };

If we have a dynamic prop for earth, we can do -

1
2
3
4
5
6
let lifeExists = "life";
const earth = { name: "earth" };
earth[lifeExists] = true;

console.log(earth);
// { name: 'earth', life: true }

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 use earth.lifeExists = ... since we are not interested in lifeExists 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.

1
2
3
4
5
6
let lifeExists = "life";

const earth = { name: "earth", [lifeExists]: true };

console.log(earth);
// { name: 'earth', life: true }

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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things