1
var fruit = {apple:"1", banana:"2"};
var w = "apple";

console.log(fruit.w); //this is problematic

I am trying to use this logic in my code to display the value "1" in the console. This doesn't work. Intuitively, this makes sense, as console.log(fruit.w); is equivalent to console.log(fruit."apple");, which because of the quote symbols is non-sense. So how can I modify this code to work?

George
  • 6,927
  • 4
  • 34
  • 67
  • see mdn about [Bracket notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Bracket_notation) – Grundy Jan 15 '15 at 04:27

2 Answers2

3

You can use:

console.log(fruit[w]);
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
1

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)

Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55