Here's why that doesn't work. It's all about scope. When you call fruit.w
, it's looking for the property w
that belongs to the fruit
object, instead of the value of global variable w
in the object fruit
.
Instead, you can use [w]
, which uses the value of global w
as the name of the property for object fruit
.
Note: Global is used in the context of the code block this resides in.
var fruit = {apple:"1", banana:"2"};
var w = "apple";
console.log(fruit[w]); // Produces '1'
This uses the value of the variable as the property by this notation.
This snippet should illustrate the point.
$(document).ready(function() {
var fruit = {
apple: "1",
banana: "2"
};
var w = "apple";
$(".apple").text(fruit[w]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="apple"></div>
Further Reading:
MDN Bracket Notation (Thanks @Grundy)