Search code examples
javascriptjsonvariablesidentifier

Using a variable as identifier in a json array


I'm wondering if it is possible to use assigned variables as identifier in a json array. When I tried this, I was getting some unexpected results:

(Code is simplified, parameters are passed in a different way)

var parameter = 'animal';
var value = 'pony';

Util.urlAppendParameters(url, {
  parameter: value
});


Util.urlAppendParameters = function(url, parameters) {
  for (var x in parameters) {
    alert(x);
  }
}

Now the alert popup says: 'parameter' instead of 'animal'. I know I could use a different method (creating an array and assigning every parameter on a new line), but I want to keep my code compact.

So my question is: Is it possible to use a variable as an identifier in the json array, and if so, could you please tell me how?

Thanks in advance!


Solution

  • No, you can't use a variable as an identifier within an object literal like that. The parser is expecting a name there so you can't do much else but provide a string. Similarly you couldn't do something like this:

    var parameter = 'animal';
    var parameter = 'value'; //<- Parser expects a name, nothing more, so original parameter will not be used as name
    

    The only work around if you really really want to use an object literal on a single line is to use eval:

    Util.urlAppendParameters (url, eval("({" + parameter + " : value})");