How can I iterate through the keys of an object, when the keys are not strings?

Viewed 66

For various configurations (parameters etc) in my app I like to use objects. The keys of the objects are not strings, but enums.

When the keys are not strings, how can I iterate through the keys and get each key as the proper enum type?

Example:

enum Color {
    RED = 1
}

let colorNames: { [key in Color]?: string } = {
    [Color.RED]: "red"
}

Object.keys(colorNames).forEach(colorsKeyStr => {

    let colorNum: Color = colorsKeyStr // <-- produces error
    // What's the proper way to cast a "color" variable to the "Color" enum type?
})
2 Answers

You can use a map if you need the key to be something else then a string.

enum Color {
  RED = 1,
}

const colorNames: Map<Color, string> = new Map();
colorNames.set(Color.RED, "red");

// Looping over map
colorNames.forEach((value, key) => {
  console.log("key", key);     // Expected: 1
  console.log("value", value); // Expected: "red"
});

// Get single value
const red = colorNames.get(Color.RED);

Another option is to cast the colorsKeyStr to a number.

enum Color {
  RED = 1
}

let colorNames: { [key in Color]?: string } = {
  [Color.RED]: "red"
}

Object.keys(colorNames).forEach(colorsKeyStr => {
  const index = Number(colorsKeyStr);
  let colorNum: Color = index;
})

The colorKeyStr returns the key which is a number. You can use the number to find the entry of the actual enum, with the Enum[enumValue] syntax.

enum Color {
  RED = 1
}

let colorNames: {
  [key in Color] ? : string
} = {
  [Color.RED]: "red"
}

Object.keys(colorNames).map(colorName => Color[Number(colorName)]
).forEach(color => {
  console.log(color);
  // You will get the correct color from your enum, but the type is still incorrect
})

Related