16

How can I make this happen:

var name = otherObject.name; //"string"
var o = { 
            name : otherObject
        };
alert(o["string"].name);
0

1 Answer 1

38

Use bracket notation instead.

var name = otherObject.name;
var o = {};
o[name] = otherObject;

Or, in modern JavaScript:

var o = {
  [name]: otherObject,
};
Sign up to request clarification or add additional context in comments.

1 Comment

Since this is a decent duplicate target, it might be helpful to be more specific than "modern JavaScript". This syntax was introduced in ECMAScript 2015, and is called a computed property name. Here's the link to the specification's ComputedPropertyName expression in case you want to cite the specification directly as well.

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.