0

I'm trying to create new object member with a dynamically created string as the member name:

  > obA = {};
  > obb = {name:'jim', age:22};
  > var s = new String(obb.name);
  > obb;                       //{ name: 'jim', age: 22 }
  > obA.s = obb;               //{ name: 'jim', age: 22 }
  > obc = {name:'don', age:23};
  > var c = new String(obc.name);
  > obA.c = obc;
  > obA;
        outputs the folowing
             { s: { name: 'jim', age: 22 },
               c: { name: 'don', age: 23 } }

In this example I would like to add members 'jim' and 'don' to obA, not 's' and 'c'. Instead my calls above add members 's' and 'c'. Is there some way to dynamically name the members so that I can add 'jim' and 'don' at runtime without knowing the member names ahead of time. What I want from in the above example from 'obA' at the end is:

  > obA;
   // should output
        { jim: { name: 'jim', age: 22 },
          don: { name: 'don', age: 23 } }
0

3 Answers 3

3

Use bracket notation.

obj['property'] = value;
Sign up to request clarification or add additional context in comments.

Comments

2

Try [] instead of dot.

obA[s] = obb;
obA[c] = obc;

Comments

1
obA[obb.name] = obb;
obA[obc.name] = obc;

1 Comment

Thanks, exactly what I wanted.

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.