Salman Salman - 3 months ago 16
jQuery Question

How to use a string as a selector in json data?

I want to use a String as a part of the addressing to json data using jQuery.

var group = "AA";
var products = {
"AA": [
{ "name": "1", "image": "/" },
{ "name": "2", "image": "/" },
{ "name": "3", "image": "/" }
]}
var name2 = products.parseSelector(group)[1].name;


The idea is to get 2 as result.
But it throws an Exception.

Any help would be appreciated.

Answer

Use bracket notation to access the object property.

var name2 = products[group][1].name;