31

Possible Duplicate:
Is a way that use var to create JSON object in key?

I would like to construct a JSON object in JavaScript by using the value of a (String) variable as the key. But what I got is the name of the variable as the key.

example.js:

function constructJson(jsonKey, jsonValue){
   var jsonObj = { "key1":jsonValue, jsonKey:2};
   return jsonObj;
}
 

The call

constructJson("key2",8);

returns a JSON -> {"key1":8,"jsonKey":2} but I would like to have {"key1":8,"key2":2}.

Does anyone know how to achieve this? seems like a simple problem but I cannot find the solution.

1

1 Answer 1

52
function constructJson(jsonKey, jsonValue){
   var jsonObj = {"key1": jsonValue};
   jsonObj[jsonKey] = "2";
   return jsonObj;
}
Sign up to request clarification or add additional context in comments.

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.