2

I have this structure:

var data = {
    'horizontal':{
         'static':[1,3,5,7,9],
         'dynamic':[2,4,6,8]
    },
    'vertical':{
         'static':[1,3,5,7,9],
         'dynamic':[2,4,6,8]
    }
};

I have this HTML objects:

Direction:
<select id="direction">
    <option value="horizontal">Horizontal</option>
    <option value="vertictal">Vertictal</option>
</select>

Type:
<select id="mytype">
    <option value="static">Static</option>
    <option value="dynamic">Dynamic</option>
</select>

Can I access to the data.horizontal.static[2] somehow like this?

var result = data.[ $('#direction').val() ].[ $('#mytype').val() ][2];

Is there any way?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
netdjw
  • 5,419
  • 21
  • 88
  • 162
  • 1
    remove dots between ']' and '[' – Ruslan Polutsygan Apr 17 '13 at 13:57
  • possible duplicate of [I have a nested data structure / JSON, how can I access a specific value?](http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value) – Felix Kling Apr 17 '13 at 14:00
  • 1
    FYI, [there is no such thing as a JSON object](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). JSON is a textual data exchange format. You simply have a JavaScript object. – Felix Kling Apr 17 '13 at 14:01

3 Answers3

1

Your syntax is close.... you need:

var result = data[ $('#direction').val() ][ $('#mytype').val() ][2];

Note (no periods between square brackets)

BLSully
  • 5,929
  • 1
  • 27
  • 43
1

try remove dots

var result = data[ $('#direction').val() ][ $('#mytype').val() ][2];
0

Not sure what value you're wanting here, but this is how you access your values:

console.log(data['horizontal']);
console.log(data['horizontal']['static']);
console.log(data['horizontal']['static'][2]);

Fiddle:

http://jsfiddle.net/jj49G/

Chris Dixon
  • 9,147
  • 5
  • 36
  • 68