0

I defined a variable which will get user's input:

var input = USER_INPUT;

then, I create an object which will use this input as an variable name inside the object:

var obj = { input: Car.newCar(...)}

Then, I try to access the obj[input], but it returns to me undefined. Is it so that in javascript, I can not use variable as an object's variable name?

If I would like to define a object which has vary variable name and variable value, how can I do?

1

2 Answers 2

2

So I guess you want the store the input under a key named after the input itself.
You can assign the value returned by Car.newCar() by using the [] method:

var input = "some text";
var obj = {};

obj[input] = Car.newCar();
Sign up to request clarification or add additional context in comments.

Comments

1

Sorry changed my answer after re-reading the question

var USER_INPUT = 'something';
var obj = {};
obj[USER_INPUT] = 'value';

obj.something ; //# => value
obj['something'] ; //# => value

obj[USER_INPUT]; //# => value

3 Comments

no, he wants to access it like you do with PHP indices. input being a variable and not fixed string
I know I was in the midst of changing my answer which I now have done. Note to self: More haste less spead :)
here, have this +1 for your troubles :)

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.