-1

I have a variable named day. It contains the current day (i.e. "Wednesday") as a string. I also have an object called data. When I alert data.Wednesday it gives me the total count for that day.

alert(data.Wednesday); //alerts 2

I want the count for the current day (not the hard-coded Wednesday). My question is, how do I replace data.Wednesday with data.day. I obviously cant do data.day because day isn't an element of the data object. Is there any way to do this? Thanks in advance.

  • Ugh, wrong duplicate. This is the correct one: http://stackoverflow.com/q/4244896/218196. Someone else please close. – Felix Kling Jun 25 '15 at 02:55

2 Answers2

2

You have to access the property by using squared brackets.

var day = "Wednesday";
alert(data[day]);
Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17
2

To let JS evaluate your expression and lookup a property with the value use square bracket notation

var data = {someValue: 'Wednesday'};
var day = 'someValue';
data[day]; // 'Wednesday'

Where someValue can be a string or a number.

t3dodson
  • 3,949
  • 2
  • 29
  • 40