10

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!

Mickael Lherminez
  • 679
  • 1
  • 10
  • 29

3 Answers3

10

You will need to build your object in two steps, and use the [] property accessor:

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

var obj = {};
obj[parameter] = value;

Util.urlAppendParameters (url, obj);

I don't think JSON Array is the more correct term, I would call it Object literal.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • Yeah, I already did that, but I just want to know if it ís possible, like in other programming languages (e.g. escaping with backticks, or just with a leading $ sign) Sorry for the vague title, programming terminology is not my best skill. – Robbert van den Bogerd Apr 29 '10 at 15:11
  • 3
    @CMS we searched the internet for a solution for a long time and found it here, thx – Michael Moeller May 26 '13 at 17:51
3

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})");
Bob
  • 7,851
  • 5
  • 36
  • 48
  • That's exactly what I was looking for. Not that I'm going to use it (I sure don't really really want it :D), but I was really curious about how it could be solved. Thanks! – Robbert van den Bogerd May 03 '10 at 08:42
1

Depending on your needs you could also build your object with a helper function;

Util.createParameters = function(args) {
    var O = {};
    for (var i = 0; i < arguments.length; i += 2)
        O[arguments[i]] = arguments[i + 1];
    return O
}

Util.urlAppendParameters (url, Util.createParameters(parameter, value, "p2", "v2"));
Alex K.
  • 171,639
  • 30
  • 264
  • 288