Search code examples
javascriptobject-literal

in javascript is it possible to construct an object literal with expressions evaluating to strings for property names?


i.e. is it possible to do this:

var fruit = "banana";
var x = {
    "app" + "le" : 5, // "apple" : 5
    function(){return "orange"} : 8, // "orange" : 8
    "" + fruit : 3 // "banana" : 3
};

Solution

  • No, you can't, you need to feed it after the first initialization :

    var myKeyName = "bar";
    x[myKeyName] = "foo";