1
\$\begingroup\$

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can use {[key]: func(val)} to create an object literal with a dynamically keyed property. \$\endgroup\$ Commented Jan 14, 2018 at 2:09
  • \$\begingroup\$ @AluanHaddad that's perfect, if you make it an answer I'll accept it. \$\endgroup\$ Commented Jan 14, 2018 at 2:12

1 Answer 1

2
\$\begingroup\$

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
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.