Initialize an object with a key at runtime Often I want to construct an object with a runtime-generated key.

Here's how I have been doing it:

function make_obj(key, func, val){
  let foo={};
  foo[key] = func(val);
  return foo;
}


Usage:

make_obj('food', x=&gt;`I like ${x}`, 'soup'); // {food: 'I like soup'}


Is there a shorter way to do this?
ECMAScript 2015 adds a new feature called computed property names.
It allows you to create a property in object literal without specifying the name for the key -- it lets you use a value of a variable.

const keyName = 'foo'
const object = { [keyName]: 21 } // { foo: 21 }


You can read about a bunch of similar things on 2ality.

In your example, that would be:

function make_obj (key, func, val) {
  return { [key]: func(val) };
}