Iterating through typescript enums in Vue using v-for

Why is the v-for loop over an enum displaying both names and values?

Is there a way to iterate only over the keys?

export enum Colors {
  "RED" = 1,
  "BLUE" =  2,
  "GREEN" = 3,
}
<template>
   <div>
      <v-chip v-for="key in Colors" :key="key">{{key}}</v-chip>
   </div>
</template>

<script lang="ts">
import {Colors} from "./Enums"
import Vue from "vue";
export default Vue.extend({
  data: () => ({
     Colors,
  }),
});
</script>

The current behavior results in 6 chips, while I expected only 3.

  • RED
  • BLUE
  • GREEN
  • 1
  • 2
  • 3

Answer №1

As v-for iterates through all properties of an object, it will display both the forward and reverse properties of the Typescript enum. To only show specific keys, you may need to manually filter the keys, potentially using Number.isInteger().

To provide some background, Typescript enums inherently include reverse mappings by default:

In addition to creating an object with property names for members, numeric enums members also get a reverse mapping from enum values to enum names. For example, in this scenario:

enum Enum {
  A,
}

let a = Enum.A;
let nameOfA = Enum[a]; // "A"

TypeScript translates this into the following JavaScript code:

"use strict";
var Enum;
(function (Enum) {
  Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

In this resultant code snippet, an enum is compiled into an object that saves both forward (name -> value) and reverse (value -> name) mappings. Any references to other enum members are always output as property accesses rather than inline.

Answer №2

Using Jeff's guidance, the final code snippet will resemble the one below:

<template>
    <div>
      <v-chip 
        v-for="([value, key], idx) in Object.entries(Colors).filter(([_, k]) => Number.isInteger(k))" 
        :key="idx"
      >
        {{ key }}
      </v-chip>
    </div>
</template>

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

Running ngAfterViewInit() code in Angular should be done only after Inputs() have been initialized

Within a particular component, I have implemented some code in ngAfterViewInit: @Input public stringArray: string[]; public newArray: string[]; ngAfterViewInit() { this.newArray = this.stringArray.filter(x => x.includes('a')); } I placed ...

A guide on utilizing the useEffect hook to dynamically update a button icon when hovering over it in a React application

Is it possible to change the icon on a button when hovering using useEffect? <Button style={{ backgroundColor: "transparent" }} type="primary" icon={<img src={plusCart} />} onCl ...

The instance is referencing the property or method "sendResetMail" during render, but it is not defined

I'm pretty new to Vue and struggling with an error message while trying to get a reset email modal working in my Vue project: The error says that the property or method "sendResetMail" is not defined on the instance but referenced during render. I ...

Ensure that reactivity is applied only to nested properties

My data object consists of properties unrelated to vue/the UI and data that represents the state. I only want the state to be reactive, but I still need the complete object in the component. It's important that vue doesn't modify the other proper ...

Having trouble connecting Nextjs with ChromaDB?

I am encountering issues while trying to establish a connection with the Chromadb vector database in Nextjs. The objective is to store user-generated content in Chromadb. Below is the code snippet I am utilizing along with its dependencies: Dependencies V ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...

Ways to designate a parent element in Vue Draggable when the element is lacking a child

I'm currently incorporating vue-draggable into my project from the following GitHub repository: https://github.com/SortableJS/Vue.Draggable Below is my ElementsList component: <div> <draggable v-model="newElement" :move ...

How to utilize a PHP array within a Vue.js template

I have been exploring the realms of Laravel and vue.js recently and have encountered a challenge. Within my Laravel model, I have a PHP method that retrieves data from a database and organizes it into objects stored in an array. Now, my goal is to access t ...

When trying to convert a jest test to typescript, an error message may be encountered stating: "SyntaxError: Unable to

As I delved into the clear and concise jest documentation, I managed to successfully implement this test: const { spawnSync } = require('child_process'); const ls = spawnSync('ls', ['-lh', '/usr']); const unexistent ...

Using Rxjs to dynamically map values from an array with forkJoin

Greetings! I have a collection of Boolean observables and would like to apply a logical AND operation. Currently, I am passing static values 'a' and 'b', but I am unsure of the number of elements in the totalKeys array. import { forkJoi ...

Select characteristics with designated attribute types

Is there a way to create a type that selects only properties from an object whose values match a specific type? For example: type PickOfValue<T, V extends T[keyof T]> = { [P in keyof (key-picking magic?)]: T[P]; }; I am looking for a solution w ...

Invoke a parent method from a nested child component in Vue

After setting up a project with vue-cli using the webpack template, I decided to incorporate a reusable bootstrap modal dialog in the App component. To achieve this, I created a method called showMessage in the App component that handles displaying the mod ...

How to retrieve the type of a computed keyof T as a generic type within TypeScript

I am working with two different interfaces: interface PersonRequirements{ user:string, password:string, id:number } export interface Requirement<R> { name: keyof R & string, save: () => any,/* I want this return type to be ...

Experiencing difficulties while attempting to organize an array?

// const first = data.groups_with_selected[7]; // const second = data.groups_with_selected[20]; // data.groups_with_selected.splice(2, 0, first, second); // data.groups_with_selected.splice(9, 1) // data.groups_with_selected ...

Issue with Angular 7 cli failing to recognize a custom TypeScript file

While working on an Angular 7 component, I encountered an issue when trying to read a custom file. The problem arises when the server restarts, even though there are no errors in the component's TypeScript file. ERROR: app/zontify-components/zonti ...

After pressing the login button, my intention is to transition to a different page

I am relatively new to web development and working with angular. I have a login component that, upon hitting the LOGIN button, should redirect to another component on a different page. However, currently, when I click the button, it loads the data of the o ...

Seeking guidance for the Angular Alert Service

I'm relatively new to using Angular and I'm struggling to determine the correct placement for my AlertService and module imports. Currently, I have it imported in my core module, which is then imported in my app module. The AlertService functions ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

Steps to troubleshoot a simple function that manages asynchronous tasks

Looking to develop a versatile function that can handle async functions, execute them, and catch any errors that may arise. Coming from a javascript background, I initially managed to create a function that did just this. However, my attempt to enhance it ...

Why is it necessary for me to constantly run npm run production in order to view any updates?

Currently, I am integrating Vue within Laravel. After making changes in the Vue code, I have noticed that these changes do not appear until I execute the following command: npm run production Is there a way to avoid having to run this command every time ...