-2
const AnimeState = Object.freeze({
    Idle = 1,
    Walking=2,
    Running=3,
    Attacking = 4,
    Dead = 0,
    Uninitialized: -1
});

this.state = AnimeState.Uninitialized

Trying to get the name of the state, console.log(AnimeState[this.state]) --- this doesn't work however, maybe because of me using the Object.freeze() method here. Is there a way to get both worlds?

Desire: console.log(AnimeState[this.state]) if state === AnimeState.Uninitialized, give me Uninitialized as string.

I followed this link: How to get names of enum entries? and there, they pointed:

enum colors { red, green, blue };

Will be converted essentially to this:

var colors = { red: 0, green: 1, blue: 2,
               [0]: "red", [1]: "green", [2]: "blue" }

Because of this, the following will be true:

colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0

This creates a easy way to get the name of an enumerated as follows:

var color: colors = colors.red;
console.log("The color selected is " + colors[color]);
Alix Blaine
  • 585
  • 2
  • 16
  • `this.state` has the value you are looking for – Konrad Apr 10 '23 at 08:44
  • @Konrad, yes `-1`, but I want it to give me the `Uninitialized` the name of the state. – Alix Blaine Apr 10 '23 at 08:44
  • 1
    Does this answer your question? [How to get a key in a JavaScript object by its value?](https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value) – Konrad Apr 10 '23 at 08:45

1 Answers1

1

The problem with the code is that you are try to use the assignment operator (=) instead of the colon (:) to define the property values of the AnimeState object. and also, you are using camelCase instead of PascalCase for the property names.

You can try this code :

const AnimeState = Object.freeze({
    IDLE: 1,
    WALKING: 2,
    RUNNING: 3,
    ATTACKING: 4,
    DEAD: 0,
    UNINITIALIZED: -1
});

let state = AnimeState.UNINITIALIZED;
console.log(Object.keys(AnimeState).find(key => AnimeState[key] === state)); 

If you that the object will be as enum:

enum AnimeState {
UNINITIALIZED = -1,
DEAD = 0,
IDLE = 1,
WALKING = 2,
RUNNING = 3,
ATTACKING = 4,
}

And then assign a value to state like this:

let state: AnimeState = AnimeState.UNINITIALIZED;
yanir midler
  • 2,153
  • 1
  • 4
  • 16