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"
}
Desired result:
// [object Object]
{
"id": "somevalue",
"name": "somevalue",
"image": "somevalue"
}
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')
)
Top comments (0)