\$\begingroup\$
\$\endgroup\$
2
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=>`I like ${x}`, 'soup'); // {food: 'I like soup'}
Is there a shorter way to do this?
asked Jan 14, 2018 at 2:05
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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) };
}
answered Sep 1, 2018 at 9:00
lang-js
{[key]: func(val)}
to create an object literal with a dynamically keyed property. \$\endgroup\$