开发者

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

开发者 https://www.devze.com 2023-03-21 15:35 出处:网络
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:

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 inste开发者_JS百科ad of the variable name? (or really I guess it's not using the variable at all, just treating 'keyVal' as the key name)


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 recommended

0

精彩评论

暂无评论...
验证码 换一张
取 消