0

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?

bobbyrne01
  • 6,295
  • 19
  • 80
  • 150
user70192
  • 13,786
  • 51
  • 160
  • 240
  • possible duplicate of [How can I display a JavaScript object?](http://stackoverflow.com/questions/957537/how-can-i-display-a-javascript-object) – Claudiu Jun 12 '15 at 17:35

3 Answers3

1

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

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

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
Claudiu
  • 224,032
  • 165
  • 485
  • 680
0

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.

amulya349
  • 1,210
  • 2
  • 17
  • 26