0

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.

Pulkit Goyal
  • 5,604
  • 1
  • 32
  • 50
artvolk
  • 9,448
  • 11
  • 56
  • 85
  • Your example is not JSON, it's just a [JavaScript object initializer](http://es5.github.com/#x11.1.5). JSON is a subset of object initialization syntax. (To be using JSON notation after the `=` and before the `;` in your JavaScript -- e.g., to restrict yourself to only the JSON subset even though you're in JavaScript code and don't *have* to -- you'd've had to be using double quotes.) – T.J. Crowder Mar 21 '12 at 10:15
  • Thanks for correction, thats not JSON really. And sorry that I doesn't mention that using indexes is not an option here. Objects can be deeeeeply nested. :) – artvolk Mar 21 '12 at 10:18
  • If you already have config, can I ask why you need obj? Seems a bit redundant. – Chris Gessler Mar 21 '12 at 10:19
  • 1
    *"Edit: I'm aware of using [], but that's not an option in case of deeply nested objects."* Sure it is. It's *awkward*, but: `var key1 = "a", key2 = "b", key3 = "c", obj = {}; obj[key1] = {}; obj[key1][key2] = {}; obj[key1][key2][key3] = 42;` is the same as `var obj = {a: {b: {c: 42}}};`. It sounds like you might need a recursive object generator function. – T.J. Crowder Mar 21 '12 at 10:19
  • I doesn't mean it doesn't work, it just not as elegant as having everything in object initializer... – artvolk Mar 21 '12 at 10:20
  • _If you already have config, can I ask why you need obj? Seems a bit redundant._ It's very special case (API of flash video player). I need to specify player's plugin name and later get it by name when it is loaded. – artvolk Mar 21 '12 at 10:20

5 Answers5

1

You can use the square bracket syntax to access a property dynamically. For example, assuming config.keyName contains the string "hello":

var obj = {};
obj[config.keyName] = "some value";

/* The above is equivalent to:

   var obj = {
       hello: "some value"
   };
*/

It's also worth noting that, as others have mentioned, this is a JavaScript object literal. It is not JSON. JSON is simply a text format commonly used for data transfer that happens to share some of the properties of JavaScript object literals.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

There is no such thing as "JSON notation" in Javascript. It's object literal notation, and JSON uses a subset of the Javascript notation, not the other way around.

You can't use variables for the property names in an object literal. You have to add the properties to the object using property indexing:

var obj = {};
obj[config.myKeyName] = "some value";
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

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:

var key1 = "a", key2 = "b", key3 = "c", obj;
obj = {}
obj[key1] = {};
obj[key1][key2] = {};
obj[key1][key2][key3] = 42;

But

var obj = {
    /*magic here using key1 to get "a"*/: {
        /*magic here using key2 to get "b"*/: {
            /*magic here using key3 to get "c"*/: 42
        }
    }
};

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 is Object.defineProperty which 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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • May be some `eval`? The last chance :) – artvolk Mar 21 '12 at 10:24
  • @artvolk: Well sure, you can use `eval` for that: `var obj = eval("{" + key1 + ": { " + key2 + ": { " + key3 + ": 42 }}}");` I wouldn't unless you have no choice, and then **only** if you're in total control of the string you're evaluating. Remember that `eval` fires up a JavaScript parser, though they're fairly fast these days. – T.J. Crowder Mar 21 '12 at 10:27
  • So there is no way to call `eval` just for key, not entire object? – artvolk Mar 21 '12 at 10:30
  • 1
    @artvolk: No. The text prior to the `:` in an [object initializer](http://es5.github.com/#x11.1.5)'s property assignment is not an expression (and to call `eval` expressions would have to be allowed there); it must be either an identifier, a string literal, or a numeric literal. It might have been handy if expressions had been allowed there, but then we couldn't have used just an unquoted identifier anymore (we'd've *always* had to say `"a": 42` rather than being able to say `a: 42`) and I figure people would have complained about that. :-) – T.J. Crowder Mar 21 '12 at 11:07
  • Thanks! It seems I should look into description of the js grammar parser first :) – artvolk Mar 21 '12 at 14:15
0
var obj = {}

obj[config.myKeyName] = 'some value';
Joel Lundberg
  • 916
  • 5
  • 6
0
var config = {
  myKeyName: 'key'
};

var obj = {
  'config.myKeyName' : 'some value' // note quote here on key
};
//console.log(obj);
Swatantra Kumar
  • 1,324
  • 5
  • 24
  • 32