0

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?

Adam Scot
  • 1,371
  • 4
  • 21
  • 41

1 Answers1

2

Here you go:

var products = {
    "prod_1": {
      "name": "Apple",
      "price": "10",
    },

    "prod_2": {
      "name": "Pear",
      "price": 9
    },

    "prod_3": {
      "name": "Grapes",
      "price": 15
    }
}
var SelectedProduct = "prod_1"
var SelectedProductName = products[SelectedProduct].name
console.log("The selected product is " + SelectedProductName)
Vincent
  • 3,945
  • 3
  • 13
  • 25