0

I want to look up a property of a Javascript object using a string inside of a variable, but when I execute the code below, the second alert returns undefined.

 <script>
    var operations = {"Create": "POST",
                      "Read": "GET",
                      "Delete": "DELETE"
    };
    //result POST
    alert(operations.Create);

    var method="Create";
    alert(operations.method); //returns undefined, I want it to return "POST"
 </script>

How do I use the "method" variable to look up the "Create" property I created at the beginning of the script?

Steven Kryskalla
  • 14,179
  • 2
  • 40
  • 42
user719852
  • 131
  • 1
  • 3
  • 8

6 Answers6

4

try

operations[method]

you can't use dot notation if you want to access by a variable. The reason is when you use dot notation, the interpreter is not using the value of the variable; it thinks the variable name itself is the key. In other words, it's looking for the key "method", not "Create".

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0

Method is not defined in your object declaration so it is doing what it should. var method is not contained within the ooerations. you want to define.

thenetimp
  • 9,487
  • 5
  • 29
  • 42
0

Operations does not have a method property. If you wanted to add that value to your object, you could do this:

operations.method = "Create";
alert(operations.method);

If you want to get the value for a specific string key, you can look it up by the indexer:

alert(operations["Create"]);
Tejs
  • 40,736
  • 10
  • 68
  • 86
0

You should do:

var method=operations.Create;
alert(method);

or

var method="Create";
alert(operations[method]);
Alex Dn
  • 5,465
  • 7
  • 41
  • 79
0

I believe you're declaring method as a separate string object. Instead of

var method="Create";

try doing

operations.method = "Create";

This will make method an actual property of the operations object, which you will be able to access either from operations.method or operations["method"].

Greg Kramida
  • 4,064
  • 5
  • 30
  • 46
0
var operations = {"Create" : "POST",
                  "Read" : "GET",
                  "Delete" : "DELETE"
                };

alert(operations.Create);

operations.method = 'Create';
alert(operations.method);

var method = 'Create';
alert(method);
osahyoun
  • 5,173
  • 2
  • 17
  • 15