1

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?

Leviathan
  • 104
  • 1
  • 8
  • do you mean u need to pick the colour corresponding to item's index? array.foreach((item, i) => { item.colour = Colours[i] }); – Gorynych Oct 27 '21 at 19:05
  • Does this answer your question? [How can I loop through enum values for display in radio buttons?](https://stackoverflow.com/questions/39372804/how-can-i-loop-through-enum-values-for-display-in-radio-buttons) – S.Nakib Oct 27 '21 at 19:15
  • @Gorynych Yes I think so, so if its the 8th item in the array, I want the 8th colour in the list – Leviathan Oct 27 '21 at 19:16

2 Answers2

2

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

jsonderulo
  • 1,241
  • 1
  • 12
  • 18
1

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

Acuao
  • 671
  • 4
  • 15