Using a variable as identifier in a json array
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.
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})");
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"));