Traverse an enumeration to assign values to a collection

I am looking to iterate through an enum in order to retrieve all the values. Let's say I have

export enum Colours{
    green,
    red,
    blue,
    brown,
    purple,
    black,
    orange,
    pink,
    yellow
}

and what I aim to achieve is

array.foreach(item => {
item.colour = Colours.value
});

Therefore, the first item in the array would be green, and so on. Is there a more effective method for accomplishing this?

Answer №1

If you want to assign colors from an enum to elements in an array, you can achieve this using a for loop. Simply iterate over the array and set the color property of each object to the corresponding color from the enum based on the index.

enum Colours{
        green,
        red,
        blue,
        brown,
        purple,
        black,
        orange,
        pink,
        yellow
    }
    
    
    const someArray = [{name: "someThing", color: "someDefaultValue"}]
    
    
    for (let i =0; i < someArray.length; i++) {
        someArray[i].color = Colours[i]
    }

For a demonstration, check out this TypeScript playground example:

Click here for the demo

Answer №2

I am enhancing the response from @lockednlevered.

If there are more entries in the array than colors, this code will loop back to the 1st color and repeat.

enum Colours{
    green,
    red,
    blue
}

const enumSize = Object.keys(Colours).length / 2;

const someArray = [{name: "someThing", color: "someDefaultValue"}, {name: "someThing", color: "someDefaultValue"}, {name: "someThing", color: "someDefaultValue"}, {name: "someThing", color: "someDefaultValue"}, {name: "someThing", color: "someDefaultValue"}, {name: "someThing", color: "someDefaultValue"}]


for (let i =0; i < someArray.length; i++) {
    someArray[i].color = Colours[i%enumSize]
}

console.log(someArray)

You may be wondering how I determined the length of the enum? Here is where I found the answer

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

A circular reference occurs when a base class creates a new instance of a child class within its own definition

My goal is to instantiate a child class within a static method of the base class using the following code: class Baseclass { public static create(){ const newInstance = new Childclass(); return newInstance; } } class Childclass ex ...

Issue: StaticInjectorError(DynamicTestModule)[FilterOptionsComponent -> Environment]:

While testing my app, I encountered an error that stated: "PhantomJS 2.1.1 (Linux 0.0.0) FilterOptionsComponent should clean fields when click in the clean button FAILED Error: StaticInjectorError(DynamicTestModule)[FilterOptionsComponent -> Environ ...

Build an Angular wrapper component for the phone textbox functionality

Looking to transform the Phone Mask solution below into an Angular component. Does anyone have a method to accomplish this? * Any solution that results in a similar component for a Phone textbox will suffice. Mask for an Input to allow phone numbers? ht ...

Passing data between Service and Component using Angular Binding

I am attempting to show a loading indicator whenever an Http Request is sent. Although I am using Angular's Http Interceptor, the style of the indicator never seems to update. In my app.component.html, I have included a loading indicator. <div ...

Enhancing Angular2 Routing with Angular4 UrlSerializer for Seamless HATEOAS Link Integration

As a newcomer to Angular4, I am currently exploring how to consume a HATEOAS API. My goal is to either pass an object that contains the self reference or the self reference link itself through the routing mechanism (for example, by clicking on an edit link ...

Encountering a Typescript error when trying to invoke a redux action

I have created a redux action to show an alert message export const showAlertConfirm = (msg) => (dispatch) => { dispatch({ type: SHOW_ALERT_CONFIRM, payload: { title: msg.title, body: msg.body, ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

Mapping JSON objects to TypeScript Class Objects

I am in the process of transitioning my AngularJS application to Angular 6, and I'm encountering difficulties converting a JSON object into a TypeScript object list. In my Angular 6 application, I utilize this.http.get(Url) to retrieve data from an AP ...

Custom Style for Form.IO Form Builder

I have integrated Form.IO's Form builder component into my react application, but I am facing issues with the styling as it appears to be off. It seems like something is missing in the setup! Feel free to check out a small project demonstrating how I ...

Struggling with defining content and background scripts while using AngularJS2 CLI to build a Chrome extension

After creating a brand new AngularJS-2 application using the cli tool from github, I discovered that running ng build compiles my sources into a /dist folder. As I am developing a chrome extension, I need to specify the location of my content script (whi ...

Revealing private and protected Typescript members within Angular 1.x's view

When integrating TS and Angular, I've noticed that everything in my controller is accessible from the view. For example, myPrivate will be visible on $ctrl. class MyController extends BaseController implements SomeInterface { private myPrivate: s ...

A guide on getting a mongoose document back from a function with TypeScript

There are two routes in my code that perform the same operation on a token to extract a user document from the database. Subsequently, each route carries out unique operations on this extracted document. In an effort to streamline the code, I am attempting ...

In my Angular project, I'm looking to show the date and time based on the specific timezone

I am currently showcasing the IST time zone, but I would like to adjust it based on the user's location. Here is an example code snippet from app.component.html: <td>{{scan.createdOn + 'Z' | date :'medium'}}</td> ...

Viewability of external values in angular designs

Currently, I am facing an issue where multiple modules have duplicated options within the class field: ... options = ['opt1','opt1'] ... To solve this problem, I want to move the duplicated options to a constants module and then im ...

Executing Multiple Requests Concurrently in Angular 5 using forkJoin Technique

Important Note The issue lies in the backend, not Angular. The requests are correct. In my Angular5 app, I am trying to upload multiple files at once using rxjs forkJoin. I store the requests in an array as shown in the code below. However, after adding ...

What is the method for applying filters to individual columns within MatTableModule in Angular?

Most guides on utilizing the MatTableModule for filtering recommend incorporating a single MatInputModule where users can input their search/filter query: <mat-form-field> <mat-label>Filter Product</mat-label> <input matInput type=&quo ...

Angular 2 fails to identify any modifications

Within my template, the links are set to change based on the value of the 'userId' variable. <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo"><img src="../../public/images/logo.png" alt="" /></a> ...

The act of importing the MatButtonModule module serves no purpose

I am developing an Angular application with the Material design framework. My goal is to incorporate the material button module into my project. Including it in app.module.ts is done as follows (excerpt from code): import { MatTableModule } from '@ ...

Best practice for managing asynchronous calls and returns in TypeScript

I’ve recently started working on an Ionic 4 project, delving into the realms of Javascript / Typescript for the first time. Understanding async / await / promise seems to be a bit challenging for me. Here’s the scenario: In one of the pages of my app ...

Ways to transfer application routing to "AngularJS" rather than "ASP.NET MVC"

My current project utilizes asp.net MVC in conjunction with angular 8 for the front end. I have successfully loaded all necessary angular files (main.*.js, polyfills.*.js, runtime.*.js) and CSS files in the index of the project. When accessing my s ...