Dynamic object property names?

How can I make this happen:

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

Answers:

Answer

Use bracket notation instead.

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

Or, in modern JavaScript:

var o = {
  [name]: otherObject,
};

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.