Dynamically retrieving JavaScript property value

50 Views Asked by At

I am trying to dynamically change the options available to a user. A user will choose either 1 or 2. Once they choose a value, I need to load the options associated with that value. Currently, i have the following:

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};

var userWants = '1';
alert(json[userWants]);

Oddly, the alert window just displays ,. I don't understand why. What am I doing wrong?

3

There are 3 best solutions below

7
On BEST ANSWER

Alerts cannot display JSON objects in their natural form. Try logging instead

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};

var userWants = '1';
console.log(json[userWants]);

Also, see how to alert javascript object

0
On

Alert converts the object to a string using .toString(), which doesn't give you nice output:

var a = {'value': 'A', 'text': 'Option - A'};
alert(a); // should alert [object Object]

You can use JSON.stringify to display the object nicely:

alert(JSON.stringify(a)); // should alert {"value":"A","text":"Option - A"}

Or:

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};
var userWants = '1';
alert(JSON.stringify(json[userWants])); // should alert a nicely-formatted list

0
On

Use console.log(json[userWants]); instead of alert.

You can view the output in console by opening it in Chrome by using the shortcut Ctrl + Shift + J or by using Firebug for Firefox in Firefox.