0

Say you have the variable, the reason I ask if it is possible to use a variable is if I were to use an input to dynamically change the var:

var str = "pineapples"
var cost = {
pineapples: "free",
apples: "£1"
}

how would it be possible to use it as an object name

document.getElementById("result").innerHTML=cost.??
Night
  • 731
  • 5
  • 14
  • [Possible duplicate](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – ajp15243 Dec 30 '13 at 14:25

2 Answers2

4

in js if variable is objects property name then [] brackets should be used

cost[str]
WebServer
  • 1,316
  • 8
  • 12
-1

Simple, add the string to the object:

cost[ str ] = inputString;

than retrieve it after:

document.getElementById("result").innerHTML = cost.str;
Phil
  • 10,948
  • 17
  • 69
  • 101
  • Using `cost.str` will attempt to find a property literally called `str` in the `cost` object. – ajp15243 Dec 30 '13 at 14:46
  • I am confused. what is the OP looking for than? – Phil Dec 30 '13 at 15:36
  • The OP doesn't appear to know about bracket notation on objects, so that is what s/he is looking for. Your answer would be correct if you retrieved the value via `cost[str]` (looks for a property whose name is the *value* of `str`) rather than via `cost.str` (looks for a property whose name is literally `str`). – ajp15243 Dec 30 '13 at 15:40