0

How can I use multiple variables name as a object name?

For example,

name = 'myname'
age  = '16'

Now I need the object name as: userObject.myname_16.another_field

5
  • Could you elaborate more on that? Cause it's not very clear what you're asking for. Commented Jun 1, 2017 at 8:54
  • Why would you want that? Can you post some more context? What have you tried? Commented Jun 1, 2017 at 8:54
  • If I understand you correctly, you can try userObject[name+'_'+age].another_field Commented Jun 1, 2017 at 8:55
  • you can use like this userObject[name +'_'+age][another_field] Commented Jun 1, 2017 at 8:55
  • stackoverflow.com/questions/4255472/… Commented Jun 1, 2017 at 8:56

2 Answers 2

2

You can access Object properties with square brackets too (bracket notation).

Try the following;

userObject[name+'_'+age].another_field

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_Accessors

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

Comments

0

Not sure what you are exactly looking for.

May be you want to create nested objects.

name = 'myname';
age  = '16';

console.log("Name",name);

var userObject = { name : { city : "NY" }};

console.log(userObject.name.city);

name = 'myname';
age  = '16';

var userObject = {};
userObject[name+"_"+age]= "Test";

console.log(userObject.myname_16);

Comments

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.