-2

I'm trying to use a variable for skillName which represents 'Tackle' and i dont want to use userBattlePokemon[0].skills.Tackle because i want my code to be more dynamic for different skills from different objects. But skillName currently represents a string, which means the enemyBattlePokemon[0].health became NaN.

For this instance, is there any way to write it so that skillName returns Tackle which is not a string and can be used in the assignment?

userBattlePokemon = [{
    skills: {
        Tackle: 5,
        LeechSeed: 10
    }
}];

enemyBattlePokemon = [{
    health: 100
}];

let skillName = userBattlePokemon[0].skills[0]

enemyBattlePokemon[0].health = enemyBattlePokemon[0].health - userBattlePokemon[0].skills[0].skillName
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Wil Son
  • 1
  • 1
  • `userBattlePokemon[0].skills[0]` will be `undefined`, hence `userBattlePokemon[0].skills[0].skillName` will throw an error (regardless of `.skillName` or what is stored in `skillName`) – Andreas Sep 29 '20 at 14:55
  • Welcome Wil Son - I'm not quite sure, if I understand what you're trying to archieve. However what I see is that you try to access `skills[0]` but `skills` is an object and not an array... – leun4m Sep 29 '20 at 14:56
  • `let skillName = userBattlePokemon[0].skills[0]` - `skillName` would be an object. How should this even work? – Andreas Sep 29 '20 at 14:56
  • The dupe to your question (but not for your code in the question): [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Andreas Sep 29 '20 at 14:58
  • The first skill property name would be `Object.keys(userBattlePokemon[0].skills)[0]` – James Sep 29 '20 at 15:23

2 Answers2

0

Hope It will solve your problem

let key="Tackle";//Leechseed could be a key 
let skillName = userBattlePokemon[0].skills[key]
hmamun
  • 154
  • 1
  • 15
  • yes, that would be one way to do it, but it will be very DRY to be repeating for multiple objects and and keys. Thanks for the suggestion! – Wil Son Oct 01 '20 at 03:11
  • The for...in loop allows you to iterate the enumerable properties of an object. In each iteration, you can get the object key and by using that you can access the property value. – hmamun Oct 02 '20 at 18:06
0

I'm not completely sure, if I understand your problem, but I would suggest structuring your object like this:

userBattlePokemon = [{
    skills: [{
        name: Tackle,
        attack: 5
    }, {
        name: LeechSeed,
        attack: 10
    }]
}];

This way you can access your skill by an index and still keep a useful name.

enemyBattlePokemon[0].health = enemyBattlePokemon[0].health - userBattlePokemon[0].skills[0].atttack
leun4m
  • 560
  • 5
  • 24
  • Thanks for the suggestion. I was trying to figure out a way to perform the callback without restructuring the whole code. But seems like it would be easier to do that. – Wil Son Oct 01 '20 at 03:10