logo

Computed Property Names

January 23, 2021

ES6 Computed Property Names allows us to dynamically generate names within object literals.

In the past we will use:

const pet1 = "dog";
const name1 = "Dino";
const pet2 = "cat";
const name2 = "Fuzzy";
const animal = {};

// We will add a property using dynamic key like so:
animal[pet1] = name1;
animal[pet2] = name2;

console.log(animal); // {dog: "Dino", cat: "Fuzzy"}

Using computed properties:

const myPet = {
  [pet1]: name1,
  [pet2]: name2,
};
console.log(myPet); // {dog: "Dino", cat: "Fuzzy"}

This can be very handy.

Another example by using a function expression:

const pets = {
  Kitty: "miau",
  Fuzzy: "woff",
};

const addProp = (obj, key, value) => ({
  ...obj,
  [key]: value,
});

const myPets = addProp(pets, "Dino", "bow");
console.log(myPets); // {Kitty: "miau", Fuzzy: "woff", Dino: "bow"}