Using a string within as a function name (Javascript)

Question

Okay so, this title maybe incorrect but I don't really know how to ask this question: I'm writing a bot using Discord.js and I'm trying to reply a string from an enum based on the message given.

const Heroes = {
VengefulSpirit: {
inCaptainsMode: true,
primaryAttribute:'Agility',
    attributeGains:{
    Strength: 2.6,
    Agility: 3.3,
    Intelligence: 1.5
    },

},
}

Here is the Input

case 'venge': case 'vengeful spirit': case 'Vengeful Spirit':
message.reply(getHeroDetails('VengefulSpirit'));

And sadly a not working output

function getHeroDetails(heroName){
var heroDetails = '';
heroDetails += 'Primary Attribute: ';
heroDetails += Heroes.heroName.primaryAttribute.toString();
heroDetails += '\n In captain\'s mode: ';
heroDetails += Heroes.heroName.inCaptainsMode.toString();
heroDetails += '\n Strength gain: ';
heroDetails += Heroes.heroName.attributeGains.Strength.toString();
heroDetails += '\n Agility gain: ';
heroDetails += Heroes.heroName.attributeGains.Agility.toString();
heroDetails += '\n Intelligence gain: ';
heroDetails += Heroes.heroName.attributeGains.Intelligence.toString();
return heroDetails;
}

Now I'm using heroName as the input string so in this scenario it would be VengefulSpirit and if I used it in replacement of heroName in all those calls, the function works correctly. I just don't know how to use heroName instead of hardcoding a function for every hero (there's like 112 of them). I'm trying to create a dynamic function so that It's shorter.


Show source
| javascript   | function   | enums   | string   2017-01-03 11:01 2 Answers

Answers to Using a string within as a function name (Javascript) ( 2 )

  1. 2017-01-03 11:01

    Use Heroes[heroName] to access keys of your Heroes object instead of Heroes.heroName .

  2. 2017-01-03 11:01

    Use: Heroes[heroName]. Dot notation won't work in this situation... Good Luck with your RPG though ;)

Leave a reply to - Using a string within as a function name (Javascript)

◀ Go back