Home > database >  Loop through an enum to set values to an array
Loop through an enum to set values to an array

Time:10-28

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related