如何将String变量用作JSON对象中的键
问题描述:
我想通过使用(String)变量的值作为键来构造JavaScript中的JSON对象。但我得到的是变量的名称作为键。
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:
example.js:
function constructJson(jsonKey, jsonValue){
var jsonObj = { "key1":jsonValue, jsonKey:2};
return jsonObj;
}
电话
constructJson("key2",8);
返回JSON - > {key1:8,jsonKey:2}但我会喜欢{key1:8,key2:2}。
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
提前thx,
ronny
thx in advance, ronny
答
function constructJson(jsonKey, jsonValue){
var jsonObj = {"key1": jsonValue};
jsonObj[jsonKey] = "2";
return jsonObj;
}