Home > Blockchain >  Combine variable value and string to use in another variable name
Combine variable value and string to use in another variable name

Time:06-02

I need to combine a variable value and a string value into one. The problem is in the function. Iam trying to pull the name of a resource in the "resources" variable and this needs to be combine with "Amount" at the end in a new variable called "resourceName". For example "FoodAmount" but it ends up giving undefined back when I try to use this in my function.

Any help would be appreciated

var resources = [
  "Food",
  "Wood",
  "Stone",
  "Coal",
  "Copper",
  "Silver",
  "Gold",
  "Diamonds"
];

var playerData = [
  {"foodName":"Food", "FoodAmount":"100"},
  {"woodName":"Wood", "WoodAmount":"0"},
  {"stoneName":"Stone", "StoneAmount":"0"},
  {"coalName":"Coal", "CoalAmount":"0"},
  {"copperName":"Copper", "CopperAmount":"0"},
  {"silverName":"Silver", "SilverAmount":"0"},
  {"goldName":"Gold", "GoldAmount":"0"},
  {"diamondsName":"Diamonds", "DiamondsAmount":"0"},
]

function updateResources() {
    for (var i = 0; i <= playerData.length - 1; i  ) {
        resourceName = resources[i]   "Amount";
        console.log(playerData[i].resourceName); // Returns undefined??
        document.getElementById(resources[i]).innerHTML = playerData[i].resourceName; // Will also return undefined but should be equel to FoodAmount for the first one and so on
    }
}

CodePudding user response:

You must use playerData[i][resourceName] (note the square brackets [...] instead of the dot .). object.property is just shorthand for object["property"] and doesn't index the object by the variable property but rather by the string "property" which yields undefined as all your objects don't have a "resourceName" property set.

CodePudding user response:

Try this:

var resources = [
  "Food",
  "Wood",
  "Stone",
  "Coal",
  "Copper",
  "Silver",
  "Gold",
  "Diamonds"
];

var playerData = [
  {"foodName":"Food", "FoodAmount":"100"},
  {"woodName":"Wood", "WoodAmount":"0"},
  {"stoneName":"Stone", "StoneAmount":"0"},
  {"coalName":"Coal", "CoalAmount":"0"},
  {"copperName":"Copper", "CopperAmount":"0"},
  {"silverName":"Silver", "SilverAmount":"0"},
  {"goldName":"Gold", "GoldAmount":"0"},
  {"diamondsName":"Diamonds", "DiamondsAmount":"0"},
]

function updateResources() {
    for (var i = 0; i <= playerData.length - 1; i  ) {
        resourceName = resources[i]   "Amount";
        console.log(playerData[i][resourceName]); 
    }
}

Because you have a string you need to call the key as an array.

  • Related