DEV Community

ktr92
ktr92

Posted on

[JS TS] How to create an object with keys based on enum

Although this rarely happens, it can be useful in some cases.

We have an enum with some values. We need to create a dynamic object with properties from the enum and some values ​​handled by some callback. This allowed us to not “hardcode” our properties in the callback hadler and reuse it for different cases.

codepen: https://codepen.io/ktr92/pen/yLRMrLo

Initial data:

enum ProductProperties {
  product_id = "id",
  product_name = "name",
  product_image = "image"
}
Enter fullscreen mode Exit fullscreen mode

Desired result:

// [object Object] 
{
  "id": "somevalue",
  "name": "somevalue",
  "image": "somevalue"
}
Enter fullscreen mode Exit fullscreen mode

Solution

JS (TS):

enum ProductProperties {
  product_id = "id",
  product_name = "name",
  product_image = "image"
}


const enum2obj = (callback) => {
  return {
      ...(Object.fromEntries(
        Object.values(ProductProperties).map((val) => [
          val,
          callback()
        ])
      )),
    }
}

console.log(
  enum2obj(() => 'somevalue')
)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)