1

type = "grass"
grassStrong = ["water", "ground", "rock"];
console.log(this[type + "Strong"])

Is there a way to get something like this to work? i have multiple lists that are "type" strong, "type" weak and it would be much easier to use these lists if I can just concatenate the container in this way. I want to put 2 strings together to get a variable

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • What is the `this` here? – Geshode Dec 27 '22 at 01:24
  • This question should not have been closed. OP's example was just how they're currently doing it, and they want to know what the correct way to do it is. – Michael M. Dec 27 '22 at 01:25
  • 2
    In practice, you never need — or _want_, really — dynamic variable names. Use a simple object instead: `const strength = "strong"; const types = { grass: { weak: [`…`], strong: [ "water", "ground", "rock" ] } };` … `console.log(obj[type][strength]);`, or something similar. – Sebastian Simon Dec 27 '22 at 01:26
  • @SebastianSimon Your comment would have been better posted as an answer, no? – Michael M. Dec 27 '22 at 01:27
  • @geshode, not sure, but when i added it originally it worked with no issue... now it isn't for some reason lol – ReinkDesigns Dec 27 '22 at 01:31
  • @SebastianSimon ``` strongType = { normal:[""], fire:["grass", "ice", "bug", "steel"], water:["fire", "ground", "rock"], grass:["water", "ground", "rock"], } pickType="grass" console.log(strongType.pickType) ``` so i tried this but still having similar issues – ReinkDesigns Dec 27 '22 at 01:40
  • 2
    @ReinkDesigns You need to use bracket notation, otherwise you're trying to access the key `pickType`, not the key stored within that variable. `strongType[pickType]` (this is shown and mentioned in the link above your question, I suggest giving that a read first if you haven't yet) – Nick Parsons Dec 27 '22 at 01:45
  • @NickParsons AHH ok makes sence – ReinkDesigns Dec 27 '22 at 01:58

0 Answers0