Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda