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?

3
  • do you mean u need to pick the colour corresponding to item's index? array.foreach((item, i) => { item.colour = Colours[i] }); Commented Oct 27, 2021 at 19:05
  • Does this answer your question? How can I loop through enum values for display in radio buttons? Commented Oct 27, 2021 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 Commented Oct 27, 2021 at 19:16

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.