0

I need to traverse a JavaScript object with a stored string.

Sample string

var x = "Desserts"

Sample Object

  {
    "dataset":
      { 
      "Categories" : 
               [
                {
                 "Desserts" : 
                   [
                    "Sweets","Ice Creams","Pastry"
                   ]
                } ,
                {
                  "Juices and Beverages" :
                   [
                    "Cold","Hot","Fresh","Sodas"
                   ]
                }
         }
   }

If I traverse the object as dataset.Categories.x, it doesn't work[returns undefined] . How can I do this?

sandipon
  • 986
  • 1
  • 6
  • 19
Aravind Bharathy
  • 1,540
  • 3
  • 15
  • 32

2 Answers2

2

You should use dataset.Categories[0][x] instead of dataset.Categories[0].x

Take a look at : dot notation or the bracket notation

var x = "Desserts",
  data = {
    "dataset": {
      "Categories": [{
        "Desserts": ["Sweets", "Ice Creams", "Pastry"]
      }, {
        "Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
      }]
    }

  }

alert(data.dataset.Categories[0][x]);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0
var obj = {
    "dataset": {
        "Categories": [{
            "Desserts": ["Sweets", "Ice Creams", "Pastry"]
        }, {
            "Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
        }]
    }
}


var x = 'Desserts';
var val = obj.dataset.Categories[0][x];
console.log(val);

JSFIDDLE.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99