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.??
1

2 Answers 2

4

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

cost[str]
Sign up to request clarification or add additional context in comments.

Comments

-1

Simple, add the string to the object:

cost[ str ] = inputString;

than retrieve it after:

document.getElementById("result").innerHTML = cost.str;

3 Comments

Using cost.str will attempt to find a property literally called str in the cost object.
I am confused. what is the OP looking for than?
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).

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.