Javascript 如何使用字符串变量作为 JSON 对象中的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13474040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use a String variable as key in a JSON object
提问by rontron
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.
我想通过使用 (String) 变量的值作为键在 JavaScript 中构造一个 JSON 对象。但我得到的是变量名作为键。
example.js:
例子.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}.
返回一个 JSON -> {"key1":8,"jsonKey":2} 但我想要 {"key1":8,"key2":2}。
Does anyone know how to achieve this? seems like a simple problem but i cannot find the solution
有谁知道如何实现这一目标?似乎是一个简单的问题,但我找不到解决方案
thx in advance, ronny
提前谢谢,罗尼
回答by Anton Morozov
function constructJson(jsonKey, jsonValue){
var jsonObj = {"key1": jsonValue};
jsonObj[jsonKey] = "2";
return jsonObj;
}

