Reputation: 69
friends! I've got a json file, a .js file, and some html.
I can read the data from the json file in the js file just fine, and it's outputting to the console.
So I have a dropdown with all 50 states, and the values are the states abbreviations. Each state was 6 different values like such:
"AK": {
"I": 0,
"II": 0,
"III": 0,
"IV": 0,
"V": 0,
"VI": 0
}
I can console the data as such: data.AK.II and it is fine.
I'm having issues achieving this: data.(the value of the option selected).II
$('select#input_56_3').on('change', function () {
var thisValue = $('select#input_56_3 option:selected').val();
var newValue = data.thisValue.I;
console.log('newValue = ' + newValue);
});
This is the error I'm getting, so 'thisValue' is coming across undefined.
Uncaught TypeError: Cannot read property 'I' of undefined
Should I be converting it some way? I think I've been staring at this too long.
Upvotes: 1
Views: 225
Reputation: 8740
Change data.thisValue.II
to data[thisValue].II
, it will work.
- Bracket notation is basically used when there's a space in key names e.g.
"full name"
etc.- Do notation is used if you are directly trying to access the values in object. If
d = {k: 1}
thend.k
andd[k]
both are fine.d = {"k v": 1}
then onlyd["k v"]
will work.
> data = {
... "AK": {
..... "I": 0,
..... "II": 0,
..... "III": 0,
..... "IV": 0,
..... "V": 0,
..... "VI": 0
..... }
... }
{ AK: { I: 0, II: 0, III: 0, IV: 0, V: 0, VI: 0 } }
>
> thisValue = "AK"
'AK'
>
> data[thisValue].I
0
> data[thisValue].II
0
>
The following will throw an exception (error).
> data.thisValue.II
Thrown:
TypeError: Cannot read property 'II' of undefined
>
Upvotes: 1
Reputation: 44087
Use square bracket notation:
var newValue = data[thisValue].I;
Upvotes: 1