最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to specify value for key in JSON map (in JavaScript)? - Stack Overflow

programmeradmin3浏览0评论

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)

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)

Share Improve this question asked Jul 19, 2011 at 13:26 blabusblabus 8454 gold badges15 silver badges25 bronze badges 1
  • If key is variable and unknown, how would u access its value? – hungryMind Commented Jul 19, 2011 at 13:30
Add a ment  | 

3 Answers 3

Reset to default 7

Use square bracket notation:

myMap[keyVal] = objVal;
        var datajson = JSON.parse(data);
        var keyArr = Object.keys(datajson);
        for ( var i = 0; i < keyArr.length; i++) {
            var val = datajson[keyArr[i]];
            }
var keyVal = "abc";
var objVal = "123";
eval("myMap." + keyVal + "='" + objVal + "'")

An alternative, but eval is not remended

发布评论

评论列表(0)

  1. 暂无评论