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?

1
  • see mdn about Bracket notation Commented Jan 15, 2015 at 4:27

2 Answers 2

3

You can use:

console.log(fruit[w]); 
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.