Javascript 用字符串遍历对象

Javascript Object traversal with String

我需要用存储的字符串遍历一个 JavaScript 对象。

示例字符串

var x = "Desserts"

示例对象

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

如果我将对象遍历为 dataset.Categories.x,它不起作用[返回未定义]。我该怎么做?

您应该使用 dataset.Categories[0][x] 而不是 dataset.Categories[0].x

看看: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]);

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.