0

Say I call following function:

var query = makeQuery("email", "foo@bar.com");

The implementation I have is:

makeQuery = function (key, value) {
    return { key: value};
}

The object I end up with is: {"key": "foo@bar.com"}, which is obviously wrong. I would like to obtain {"email": "foo@bar.com"} instead. I tried setting it like so:

makeQuery = function (key, value) {
    return { JSON.stringify(key): value};
}

... but I get a "SyntaxError: Unexpected token ." I've also thought of using toString() and even eval(), without success. So my problem is to be able to set the property of the object returned in makeQuery() using its real value, that is, pick up the value of 'key', not setting the property with the 'key' literal.

Thanks for the help.

titusmagnus
  • 2,014
  • 3
  • 23
  • 23

3 Answers3

4

Create the object first and then use the square bracket syntax so you can set the property using the value of key:

makeQuery = function (key, value) {
    var query = {};
    query[key] = value;
    return query;
};
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • This one gets my vote because the function reads better. The other solutions work as well. Thanks for the help! – titusmagnus Jul 07 '13 at 17:42
0

For variable keys in objects, use

var obj[key] = value

So then it becomes:

function makeQuery(key, value) {
    var obj = {};
    obj[key] = value;
    return obj;
}
Schleis
  • 41,516
  • 7
  • 68
  • 87
0

define an object..

makeQuery = function (key, value) {
 var o = {};
 o[key] = value; 
 return o;
}
cocco
  • 16,442
  • 7
  • 62
  • 77