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?
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”.