0

Does anyone know haw to use a string to access a a javascript object? I need to use a var/string to access a javascript object.

++ This Question has been answered - See the JSFiddle for the fix ++

var answers = {"A":0,"B":0,"C":0,"D":0};

var abcd = $(this).attr("data-filter"); //this is equal to A
var answer_select = "answers."+abcd;    //this is equal to answers.A

answer_select=20; //does not change the value.
//if i write..
answers.A=20; //it works

//I need to use the variable "answer_select" as this changes each time..

I have setup a jsfiddle here..
http://jsfiddle.net/jstleger0/h3SEX/6/

jstleger0
  • 105
  • 1
  • 14

1 Answers1

2

Use this syntax: var answer_select = answers[abcd];

Boris
  • 577
  • 4
  • 15
  • I have tried : var answer_select = "answers["+abcd+"]"; With no success, it's strange. Thank you for the response. – jstleger0 Jul 29 '14 at 16:18
  • @jstleger0: No quotes! It's not a string literal you want to access or even build! – Bergi Jul 29 '14 at 16:19
  • I have tried: var answer_select = answers.abcd; and: var answer_select = answers[abcd]; when a variable is used to construct the access to the object it doesn't work.. – jstleger0 Jul 29 '14 at 16:22
  • Hey just got this.. Thanks for your help! – jstleger0 Jul 29 '14 at 16:38