dynamic keys for object literals in Javascript

RobertPitt picture RobertPitt · Jun 28, 2011 · Viewed 44.1k times · Source

Ok so I'm working away on a project in Nodes, and I've come across a small problem with the keys in object literals, I have the following set-up:

var required = {
    directories : {
        this.applicationPath                    : "Application " + this.application + " does not exists",
        this.applicationPath + "/configs"       : "Application config folder does not exists",
        this.applicationPath + "/controllers"   : "Application controllers folder does not exists",
        this.applicationPath + "/public"        : "Application public folder does not exists",
        this.applicationPath + "/views"         : "Application views folder does not exists"
    },
    files : {
        this.applicationPath + "/init.js"               : "Application init.js file does not exists",
        this.applicationPath + "/controllers/index.js"  : "Application index.js controller file does not exists",
        this.applicationPath + "/configs/application.js": "Application configs/application.js file does not exists",
        this.applicationPath + "/configs/server.js"     : "Application configs/server.js file does not exists"
    }
}

Ok so many of you will look at this and think it look's OK, but the compiler keeps telling me that I am missing a : (colon), which im not, it seems like the + or and the . are both effecting the compiler.

Now i believe (not sure), that object literals are created at compile time, and not run-time, meaning that dynamic variables such as this.applicationPath and concatenation are not going to be available :( :(

What's the best way to overcome an obstacle like this without having to rewrite large chunks of code.

Answer

Rich Apodaca picture Rich Apodaca · Aug 4, 2016

Computed property names are supported in ECMAScript2015:

var name = 'key';
var value = 'value';
var o = {
  [name]: value
};
alert("o as json : " + JSON.stringify(o));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer