0

Say I call following function:

var query = makeQuery("email", "[email protected]"); 

The implementation I have is:

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

The object I end up with is: {"key": "[email protected]"}, which is obviously wrong. I would like to obtain {"email": "[email protected]"} 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.

1
  • myDOMElement.setAttribute("attName","attValue"); might help also Commented Jul 7, 2013 at 17:36

3 Answers 3

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; }; 
Sign up to request clarification or add additional context in comments.

1 Comment

This one gets my vote because the function reads better. The other solutions work as well. Thanks for the help!
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; } 

Comments

0

define an object..

makeQuery = function (key, value) { var o = {}; o[key] = value; return o; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.