使用变量访问JSON属性(String)

使用变量访问JSON属性(String)

问题描述:

我正在尝试使用我正在通过函数传递的变量来访问JSON:

I'm trying to access a JSON using a variable I'm passing through a function:

function highlightCategory (category) {
   for (var i in data) {
      console.log(data[i].category)
   }
}

显然,这不起作用,因为'category'是我传递的函数,而不是属性的真实名称,但我我一直在尝试不同的可能性。
提前致谢!

Obviously, this doesn't work, because 'category' is what I'm passing with the function and not the real name of the property, but I've been trying different possibilities unsuccessfully. Thanks in advance!

data[i][category]

JS中的

obj.prop 是同义词 obj ['prop']

var foo {
  bar: 'baz'
};
// foo.bar == foo['bar'] == 'baz'

此外,你正在处理一个javascript对象,而不是JSON(虽然它可能有发起

Also, you're dealing with a javascript object, not JSON (though it may have originated there)