0

I have an array of objects for example this object:

new: {
  name: 'New',
  image: <LightningFilter style={styles.queryImage}/>,
  selectedImage: <LightningWhiteFilter style={styles.queryImage}/>,
  dataFunc_Chefs: getNew_Chefs,
  dataFunc_Recipes: getNew_Recipes,
},

and I have a variable to check if I am selecting Chefs or Recipes what I want to do is for example if Chefs is selected call dataFunc_Chefs how can I do that using string ?

For example, I want to call this:

var category = 'Chefs';
`new.dataFunc_${category}()`

I know this doesn't work but this is what I mean

I know I can use if and else and check the variable and call the function accordingly, but lets say I have many functions how do I acheive that

SDB_1998
  • 305
  • 5
  • 18

1 Answers1

1

Hope this is what you are looking for.

You just need to access dataFunc_Chefs object from your object using string literals.

function getNew_Chefs() {
    console.log('getNew_Chefs executed');
}
function getNew_Recipes() {
    console.log('getNew_Recipes executed');
}
const myObj = {
    name: 'New',
    dataFunc_Chefs: getNew_Chefs,
    dataFunc_Recipes: getNew_Recipes,
}
var category = 'Chefs';
myObj[`dataFunc_${category}`]()
Nitheesh
  • 19,238
  • 3
  • 22
  • 49