Computed Property Names in JavaScript

Computed Property Names is an ES6 feature which allows the names of object properties in JavaScript object literal notation to be determined dynamically, i.e. computed.

JavaScript objects are really dictionaries, so it was always possible to dynamically create a string and use it as a key with the syntax object[‘property’] = value.

However, ES6 Computed Property Names allow us to use dynamically generated names within object literals. Example:

const myPropertyName = 'c'

const myObject = {
  a: 5,
  b: 10,
  [myPropertyName]: 15
} 

console.log(myObject.c) // prints 15

To stress that expressions can be used directly as computed property names, another example:

const fieldNumber = 3

const myObject = {
  field1: 5,
  field2: 10,
  ['field' + fieldNumber]: 15
}

console.log(myObject.field3) // prints 15

This can be very handy.

One more variation is to use template literals (string interpolation) for the computed property names — note that this still requires the square bracket syntax, however:

const fieldNumber = 3

const myObject = {
  field1: 5,
  field2: 10,
  [`field${fieldNumber}`]: 15
}

console.log(myObject.field3) // prints 15

 

Access the Clipboard Through the Terminal in macOS

macOS provides a very handy way to share data between graphical (GUI) applications and command-line (terminal) tools.

This is especially useful for working with APIs using JSON (or XML) which require large payloads.

The two binary commands are pbcopy and pbpaste: short for Pasteboard Copy and Pasteboard Paste respectively (the macOS term for Clipboard).

  • pbcopy takes the standard input and copies it to the pasteboard
  • pbpaste takes the pasteboard data and copies it to the standard output

Suppose we have a sample payload in file.json. We can send its contents to the clipboard by piping the data to pbcopy:

$ cat file.json | pbcopy

Now, we simply press Command+v in a GUI app like Postman or Insomnia.

In reverse, we can press Command+c in a GUI app and then in the terminal:

$ pbpaste
{
  "data": "test"
}

Or, redirect the standard output to a file:

$ pbpaste > file.json

Or, pipe the data straight into a another command, like the super-handy JSON viewing tool fx:

$ pbpaste | fx

Note that these commands are macOS specific; they do not exist in Linux.