0

Is there a short form of doing such operation:

function doObject(key, value){
   let object = {};
   return object[key] = value;
}

UPD: forget about function, I use it just to isolate scope and provide to params key and value. I don't need to implement the function but logic that it does

Stepan Suvorov
  • 25,118
  • 26
  • 108
  • 176

2 Answers2

3
const doObject = (key, value) => ({[key]: value});
//               ^^^^^^^^^^^^    ^ ^^^^^
//               1               2 3
  1. Arrow function syntax
  2. Wrapping with braces allows you to return an object literal without the extended syntax. (Otherwise, it thinks the {} are the block delimiters.
  3. Computed object literal property key.
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

You can use a computed property name for the object:

function doObject(key, value){
   return {
       [key]: value
   };
}
nils
  • 25,734
  • 5
  • 70
  • 79