Published on

Using ES6's computed values for Object Keys and Get Rid of Shotgun Surgery

Authors

Today I had to enhance some code by changing some hard coded values to something else. Unfortunately these values were hard coded all over the code base so I had to do some shotgun surgery to update them. To avoid having to do this again in future I created constants of these values:

//these constant names make sense in this contrived business context ;)
export const FOO = 'hahaha'
export const BAR = 'blahblah'

The problem was I had some JavaScript associative arrays (AKA JavaScript objects) which I also wanted to use these constants for. Luckily I discovered that ES6 has support for this using a slightly weird syntax. So before I had something like:

const myObject = {
  hahah: 1,
  blahblah: 2,
}

Using this ES6 feature I can change this to:

const myObject = {
  [FOO]: 1,
  [BAR]: 2,
}

Where I use the constants FOO and BAR that I defined in another file.