开发者

Access a JSON member via string?

开发者 https://www.devze.com 2023-04-01 03:38 出处:网络
My JSON: json_filter = {\"CO\": \"blah\"} I am trying to access the member \'CO\' by a string value. However, the result is undefined.

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 'CO'
console.log(json_filter.selectedState);

I was thinking eval() might work,开发者_开发技巧 but eval() == the devil :) Is there a better way to do this?


Like this:

console.log(json_filter[selectedState])


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]


Use brackets

json_filter[selectedState]


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 whatever
var val = json_filter[str]; // will give you blah


Use the bracket notation.

json_filter[selectedState];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号