Use variable as the value for key of an Object - in React-native

Viewed 946

Developer Level - I have recently started in coding languages like JS/React/React-native...

Project Language - React Native (with expo)

Problem - How do I mention a variable when calling out to values in an object.

CODE-

I have this Object in my react-native project -

export const collectionItemThemes = {
    themeColor: {
        character: "245,101,101",
        actor: "218,55,55",
        drink: "255,99,71",
        food: "56,161,105",
        object: "237,137,54",
        carBrand: "56,178,172",
        action: "90,103,216",
        emotion: "159,122,234",
    }
}

In the main file, I get the key stored in a variable like -

const theme = "character" or const theme = "food"

Now , how do I call this variable when to using the respective value from the Object above.

type = collectionItemThemes.themeColor.**the variable goes here** 

I have tried the following -

themeColor = collectionItemThemes.themeColor.type 
themeColor = collectionItemThemes.themeColor.[type]  

But these doesn't work.

Someone please help me with how the syntax goes in such situations.

2 Answers

You were close, remove the .. This is a computed property name.

themeColor = collectionItemThemes.themeColor[type] 

I tried {collectionItemThemes.themeColor[key] and it works fine.

You were trying {collectionItemThemes.themeColor.[key] which is wrong.

Here is my snack where i tried it; https://snack.expo.io/@irfanwani/obj

Related