For the following tree
var items = {
'drinks': [
{
'name': 'coke',
'sugar': '1000'
},
{
'name': 'pepsi',
'sugar': '900'
}
]
};
Is there a way to do something like
function get_values(data) {
var items = JSON.parse(items)
return items.data[0].name;
}
get_values('drinks');
If you wish to use the contents of a variable as the accessor for a property, you must use array syntax:
In your case, you need something like:
Note that this is specifically only returning the name of the first element in the array
items.drinks.