Logo

dev-resources.site

for different kinds of informations.

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

Published at
4/26/2023
Categories
enum
typescript
javascript
Author
ktrblog
Categories
3 categories in total
enum
open
typescript
open
javascript
open
Author
7 person written this
ktrblog
open
[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
enum Article's
30 articles in total
Favicon
Mastering ENUMs in Go
Favicon
The 3 kinds of Enum in Rails
Favicon
Enhancing Enum Constants in Laravel with Description and Label Attributes
Favicon
Should I stay or should I go? Enums in TypeScript - error case study
Favicon
Effective Enum
Favicon
Result in Rust: another way of error handling
Favicon
How to convert a TypeScript built-in enum to a GraphQL enum
Favicon
Leveraging Enums in Angular: Enhancing Code Clarity and Reliability
Favicon
Typescript enum vs. "as const"
Favicon
Enum Fábrica Solitão em Java
Favicon
Implementing Enums in Golang
Favicon
Elixirでリストの最初の要素を取得
Favicon
[JS TS] How to create an object with keys based on enum
Favicon
Enum ou Enumerations no PHP
Favicon
Replacing If-Else Statements with Enums in Java
Favicon
Dart enhanced enum with custom values
Favicon
Working with Enums in Rust
Favicon
Modelando algoritmos complexos com enum
Favicon
Managing Task Status Transitions in TypeScript with Enums and Object Mapping
Favicon
TypeScript Enum's vs Discriminated Unions
Favicon
Strategy Pattern no Spring Boot Usando Enum
Favicon
Problem in C Pointer
Favicon
Merge TypeScript Enums
Favicon
Agora sim, o grande ganho do enum no Dart 2.17
Favicon
How to proper use ambient enum from Definition file
Favicon
O Poder da Classe Enum com métodos abstratos
Favicon
Refactoring code with the Strate Pattern
Favicon
🔥Input Enums for a better Development Experience 🔥 😋✂️
Favicon
O pequeno grande ganho do enum no Dart 2.15
Favicon
Typescript enums drawbacks and solutions

Featured ones: