0

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
    }
}

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this worked just the way I wanted it to!
0

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.

1 Comment

Thank you for your answear too, this helped visualize what I needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.