Why does Object.values()
and Object.keys()
always give both the keys and the values?
Consider the following code:
enum Enum {
FOO,
BAR
}
console.log(Object.values(Enum));
console.log(Object.keys(Enum));
The output of this would be:
[ 'FOO', 'BAR', 0, 1 ]
[ '0', '1', 'FOO', 'BAR' ]
Why does it do that and how do I only get the keys and values?
To get the values of enum entries we can use name keys of enum object as shown below. Or we can directly get names of enum object using Object. keys() method.
To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) . The Object.
An enum is a data type that can be created by a Java programmer to represent a small collection of possible values. Technically, an enum is a class and its possible values are objects. Enums will be our first example of adding a new type to the Java language.
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
That's how enum
types are transpiled by TypeScript.
enum Enum {
FOO,
BAR
}
will become
"use strict";
var Enum;
(function (Enum) {
Enum[Enum["FOO"] = 0] = "FOO";
Enum[Enum["BAR"] = 1] = "BAR";
})(Enum || (Enum = {}));
Notice that both numeric keys and string keys are provided for easy mapping to and from both types, enabling you to do something like this:
const value = Enum.FOO; // inferred type Enum.FOO
const key = Enum[value]; // inferred type string
If you want to get an array of only the numeric or string keys, you can do this:
const numericKeys = Object.keys(Enum).map(x => parseInt(x)).filter(x => !isNaN(x));
const stringKeys = Object.keys(Enum).filter(x => isNaN(parseInt(x)));
Or for the numeric or string values (requires the es2017
library in your tsconfig
):
const numericValues = Object.values(Enum).filter(x => typeof x === "number");
const stringValues = Object.values(Enum).filter(x => typeof x === "string");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With