Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
Loop through an enum to set values to an array

I want to loop through an enum to get all the values. If I have

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

and what I want to do is

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

So first one of the array would be green. So on so forth. Unless there is a better way of doing this?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can use a for loop to get the index of your array and set the property of the object at that index to the enum with the same 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]
    }

heres a playground example

https://www.typescriptlang.org/play?#code/KYOwrgtgBAwg9gGzmATgZwN4Cgq6gcxWFABoc8iATMvKAIwTGBrzpTgHcQXcAHVXgmblcDAIYBjANY8ocFGJD5htXgEsQMkVACewBEg5YAvljMS4INABcoaOBGABBFAp1QAvFADaGEGMcALigAIntHABUACw18EJIoCyQUYLCHYAARYAAzMTAEawA1MUZgEOMAXTMsbPkoAAohWzVPAAYAbigWgB47dJc3ADohJWsozrUAakmASihsWnDnVzEdbzUKwaS6r3gkVDR1qtMsCytEYGG4fHqlgdWZoA

over 4 years ago · Santiago Trujillo Denunciar

0

i'm just improving the @lockednlevered's answer.

If theres more entries in the array than colors, this code restarts from the 1st color and so on.

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 asking how i found the way to get the emun lenght ? On this question

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda