Stephen Sun

Software engineer based in Houston, Texas.

I'm a detail-oriented individual who thrives in fast-paced team environments. I have experience across different industries, working with both front end and back end technologies.

How to add dynamically named properties to objects

Link to code snippet: GitHub

One of the great features of ES6 is computed property names.

Let's say we have the following properties:

const a = 'age'
const j = 'j'

And a person object:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  [a]: 25,
  [`${j}ob`]: 'Software Developer'
}

As long as we have brackets around our expressions, these expressions will be dynamically translated into the string used as the key.

This includes template literals and string concatenation.

If we now log the person object, we would get the following result:

{
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  job: 'Software Developer'
}

This method can also be used in functions without the need of creating an object! Passing in the two properties into our createPerson function gives the same result:

const createPerson = (a, j) => {
  return {
    firstName: 'John',
    lastName: 'Doe',
    [a]: 25,
    [`${j}ob`]: 'Software Developer'
  }
}