Retrieve all enum values using TypeScript

When dealing with a TypeScript enum like the one shown below:

export enum Color {
    Red,
    Green,
    Blue,
}

I am trying to extract all its values into an array as follows:

["Red", "Green", "Blue"]

However, when I attempt to do so using the code:

const colors = Object.keys(Color);

The resulting array is not what I expected, it includes both index and value entries:

[ '0', '1', '2', 'Red', 'Green', 'Blue' ]

Can someone explain why this is happening and provide a solution to only retrieve the values?

Answer №1

To remove the numeric keys, you can utilize either Object.values or Object.keys:

const colors = Object.keys(Color).filter((item) => {
    return isNaN(Number(item));
});
console.log(colors.join("\n"));

This code will display:

Red
Green
Blue

When a TypeScript enum is transpiled, it becomes a regular JavaScript object:

{ 
  '0': 'Red', 
  '1': 'Green',
  '2': 'Blue',
  Red: 0,
  Green: 1,
  Blue: 2
}

This means you can use the numerical index as the key to retrieve the value and vice versa:

console.log(Color[0]); // "Red"
console.log(Color["0"]); // "Red"
console.log(Color["Red"]) // 0

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shuffle elements within a multi-dimensional array

I am currently using a multidimensional array (board[10][20]) to keep track of a character's position on a game board. In order to enable user movement, I have implemented a method called movePlayer(), which updates the index where 'G' is si ...

C language implementation for quickly computing the cumulative sum of an array

Looking for a way to efficiently calculate the cumulative sum over a one-dimensional array of type double, my initial implementation turned out to be slow. Despite creating an empty array and populating it with cumulative sums in a loop, the performance wa ...

Transform an array into an unsigned whole number

Greetings! I am working with a two-dimensional array[8][8] in C programming, where the elements are either 1 or 0. My query is: What is the best way to transform an entire row into an 8-bit unsigned integer? Thank you for your assistance! ...

Exploring the ngModel directive implementation within a text input field

I'm facing an issue with displaying data in input forms. <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text text-white" style="background-color:#03a9f4">Product ID</span& ...

Issue TS2304: Unable to locate symbol 'ITokenResponse'

I encountered this error message: Error TS2304: Unable to locate the name 'ITokenResponse'. Even after trying to import as suggested in a StackOverflow response, I encountered another error: Error TS2306: File 'C:/Repository/MAngular/sr ...

How can TypeScript rules be incorporated into a Next.js project without compromising next/core-web-vitals?

In my current NextJS project which is in typescript, I have the following configuration in my .eslintrc.json: { "extends": "next/core-web-vitals" } Now, I want to include additional typescript rules, such as enforcing the rule of n ...

The Angular HTTP GET request is failing to function properly as expected

I am currently working on developing the front end for an API request. The structure of the response model is as follows: export class User { ID: number; first_name: string; last_name: string; isAdmin: boolean; } Within the user.component ...

Tips for utilizing the count function alongside the group by clause for the entire document in MongoDB

I have a database structured as follows [ { _id: ObjectId("1"), name: "John Doe", age: 25, address: { street: "123 Main St", city: "New York", s ...

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...

Searching for document based on date stored as an array in MongoDB

Here is an example of a document: { "_id":"ADANIGREEN", "longcount":6," shortcount":0, "trend":"Y", "shortdate":[{"$date":"2020-07-13T00:00:00.000Z"}], "longdate ...

Incorporating an external HTML template into an AngularJS 1.5 component with the powerful combination of Webpack and Types

I am attempting to incorporate an external html file into my Angular component: import { LoginController } from './login.controller'; import './login.scss'; import './login.html'; class LoginComponent implements ng.IComponen ...

Ways to modify the datepicker format in Angular Material

I am currently facing an issue with the date format generated by the angular material datepicker...Wed Nov 21 2018 00:00:00 GMT+0530 (India Standard Time) My requirement is to receive the date in either (YYYY-MM-DD) or (YYYY-MM-DDTHH:mm) format. Here is ...

Angular Ionic calendar date selector

I'm encountering an issue while trying to implement a time picker with a minimum and maximum hour range from 10:00 am to 10:00 pm. Unfortunately, I have discovered that I cannot achieve this using the ion-datetime component. Are there any alternative ...

The issue with the jQuery array count functionality

After clicking the button with an id of #file_add_btn, my form dynamically appends a file input: <input type="file" class="btn_browse" name="file_uploads[]"> To keep track of filenames and prevent duplicates, I initialize an array. However, when a ...

In Angular 2, the geological coordinates are not saved as variables. Currently, I am attempting to showcase the latitude and longitude values on an HTML page

let lat; let lng; getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(this.showPosition); } else { alert("Geolocation is not supported by this browser."); } } showPosition(position) { console.log("Latitu ...

Using NodeJS to incorporate an array of strings into a PostgreSQL query

I'm currently working on a PostgreSQL query in Node.js using a pool created with the node-postgres package. The goal is to insert a new row into a table where one of the columns is of type text[]. Here's my code snippet: pool.query('INSERT I ...

Creating placeholder values with keys in PHP arrays can be achieved by using the array_fill_keys

How can we programmatically generate dummy data based on a given number in PHP? For instance, if we set $var=2, the script should generate two entries in an array. If we set $var=100, it should create 100 entries following a specific format using arrays i ...

Updating an Observable in Angular 4 using HttpClient's get method

Seeking assistance in updating an observable retrieved in html format from an API call. If anyone has any insights on how to achieve this, your help would be greatly appreciated. The corresponding html (in another component) is: <common-content [them ...

How can we organize an array with timestamps as keys in descending order?

Can the krsort() function effectively sort an array with timestamp keys in reverse order? Are there any other commonly used functions for achieving this type of sorting? $arr = array(); $arr[1327305600] = '87718'; $arr[1327132800] = '87798& ...

Most effective method for populating a mixed type byte array at present

Is there a simple method to organize different pieces of data into specified byte ranges when sending and receiving a byte stream? So far, I've been able to convert individual primitive datatypes into bytes, but I'm looking for a way to allocate ...