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)

1
  • If key is variable and unknown, how would u access its value? Commented Jul 19, 2011 at 13:30

3 Answers 3

7

Use square bracket notation:

myMap[keyVal] = objVal;
Sign up to request clarification or add additional context in comments.

Comments

0
        var datajson = JSON.parse(data);
        var keyArr = Object.keys(datajson);
        for ( var i = 0; i < keyArr.length; i++) {
            var val = datajson[keyArr[i]];
            }

1 Comment

Please refer the docs for formatting an answer. It would be really helpful to you to format future answers. Better formatted answers have higher rate of acceptance.
-1
var keyVal = "abc";
var objVal = "123";
eval("myMap." + keyVal + "='" + objVal + "'")

An alternative, but eval is not recommended

2 Comments

eval("myMap." + keyVal) probably returns undefined, and should result in an Invalid Lefthand Assignment error in the context you used it in. What you wanted to write was eval("myMap." + keyVal + '="' + objVal + '"'), but that is just as wrong for different reasons.
Oops yes eval("myMap." + keyVal + '="' + objVal + '"') is right syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.