For more tips like this, sign up to the weekly newsletter!

Dynamic object property

When you define objects using object literals, you can supply their properties. This is a concise way to initialize an object:

const o = {
  a: 1,
  b: 2
}; // {"a": 1, "b": 2}

But what about dynamic property names? For example, there is a variable, and you want the property name to match the variable's value.

This approach obviously does not work:

const prop = "myprop";

const o = {
  prop: "propValue"
}; // {"prop":"propValue"}

One way is to add the property later, using the assignment operator:

const o = {
  a: 1,
  b: 2
}; // {"a": 1, "b": 2}
o[prop] = "propValue"; // {"a":1,"b":2,"myprop":"propValue"}

This works, but the object's initialization is now broken into separate steps. An accidental modification may insert more lines between the creation and the dynamic set, which is what we want to avoid.

Fortunately, the square bracket notation makes setting a dynamic property name possible:

const o = {
  a: 1,
  b: 2,
  [prop]: "propValue"
}; // {"a":1,"b":2,"myprop":"propValue"}
Try it
References
Learn more: