I have some JSON data which looks like this:
var products = {
"prod_1": {
"name": "Apple",
"price": "10",
},
"prod_2": {
"name": "Pear",
"price": 9
},
"prod_3": {
"name": "Grapes",
"price": 15
}
}
I have a variable called SelectedProduct
which is equal to either prod_1
, prod_2
or prod_3
.
I want to create a new variable which is equal to the name
string of the SelectedProduct
.
So for example
when SelectedProduct = prod_1
, name
should equal Apple
and
when SelectedProduct = prod_2
, name
should equal Pear
I have tried to create a create a new variable that is a string and a variable like this:
var name= 'products.'+SelectedProduct'+'.colour';
This however simply creates a variable with the textual content of the variable name.
Is there a way in javascript that I can combine a string with a variable?