Skip to content Skip to sidebar Skip to footer

Access A Json Member Via String?

My JSON: json_filter = {'CO': 'blah'} I am trying to access the member 'CO' by a string value. However, the result is undefined. var selectedState = $(this).val(); // Selected 'C

Solution 1:

Like this:

console.log(json_filter[selectedState])

Solution 2:

json_filter.selectedState tries to look up the value with key "selectedState" in your object, which doesn't exist. Instead, to look up a value using a variable or expression as your key, use the bracket/subscript notation:

json_filter[selectedState]

Solution 3:

Use brackets

json_filter[selectedState]

Solution 4:

First of all, your JSON is not valid. It should use double quotes:

json_filter = {"CO": "blah"}

Secondly, to access the member by a string value, you can use this trick:

var str = "CO"// or selectedState or whatevervarval = json_filter[str]; // will give you blah

Solution 5:

Use the bracket notation.

json_filter[selectedState];

Post a Comment for "Access A Json Member Via String?"