I’d like to create JavaScript object on the fly using javascript object initializer notation, but take keys from config, so instead of
var obj = {
'key' : 'some value'
};
I’d like to have:
var config = {
myKeyName: 'key'
};
var obj = {
config.myKeyName : 'some value' // this will not work, just to illustrate
};
The question is how to place value of config.myKeyName in this situation.
Is this possible?
Edit: I’m aware of using indexing ([]), but that’s not an option in case of deeply nested objects.
From your comments and edit, your question seems to be: For deeply nested objects, can I have the keys be dynamic but still have the object initializer syntax.
E.g., not:
But
The answer is no, there isn’t any way to do that except
eval. The keys in an object initializer cannot be derived from variables. The[]notation is the best option for using a string to define a property name (the only other option I can see isObject.definePropertywhich would be far worse and is ES5-only). For your deeply-nested structures, it sounds like you’re going to want a recursive factory function of some kind.