DEV Community

ktr92
ktr92

Posted on

2

[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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay