开发者

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 '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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜