如何为 JSON 映射中的键指定值(在 JavaScript 中)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6747886/
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 specify value for key in JSON map (in JavaScript)?
提问by blabus
I probably am using the wrong terminology here but this is what I'm trying to do. I want to create a map with a value for each key and a value for each key's object. So using this code:
我可能在这里使用了错误的术语,但这就是我想要做的。我想创建一个映射,每个键都有一个值,每个键的对象都有一个值。所以使用这个代码:
var myMap = {};
var keyVal = "abc";
var objVal = "123";
myMap.keyVal = objVal;
Now what I want to return is a JSON object that looks like {"abc":"123"}
but instead it returns {"keyVal":"123"}
. How can I get it to use the actual variable contents for the key instead of the variable name? (or really I guess it's not using the variable at all, just treating 'keyVal' as the key name)
现在我想要返回的是一个 JSON 对象,它看起来像,{"abc":"123"}
但它返回{"keyVal":"123"}
. 我怎样才能让它使用键的实际变量内容而不是变量名?(或者我真的猜它根本没有使用变量,只是将“keyVal”视为键名)
回答by Quentin
回答by user3020489
var datajson = JSON.parse(data);
var keyArr = Object.keys(datajson);
for ( var i = 0; i < keyArr.length; i++) {
var val = datajson[keyArr[i]];
}
回答by hungryMind
var keyVal = "abc";
var objVal = "123";
eval("myMap." + keyVal + "='" + objVal + "'")
An alternative, but eval is not recommended
一种替代方法,但不推荐使用 eval