从json中的动态键值获取数据

Aut*_*Eta 13 javascript json key-value

要求如下:
我必须从页面获取位置字段.

var input= global.input = document.getElementById("Location");
Run Code Online (Sandbox Code Playgroud)

根据输入显示json文件中的邻域区域并在页面上显示.

我有一个json对象,必须根据键值(位置)过滤json对象的数据

var inputLocation=input.value;
Run Code Online (Sandbox Code Playgroud)

在我的javascript中,如果我使用动态密钥,我会收到错误.

如果我这样做,我能够得到json数组,data.Aspen但是我必须从文本字段中获取数据,它可以是不同的,所以如果我调用data.inputLocation ...它的未定义

当我使用时data.(inputLocation.value)收到以下错误:

XML过滤器应用于非XML值({Aspen:[{ID:

{
 "Aspen":[
 {
  "ID":"Bellaire",
  "Name":"Bellaire"
 },
 {
  "ID":"Champions Forest",
  "Name":"Champions Forest"
 },
 {
  "ID":"Highland Village",
  "Name":"Highland Village"
 },
 {
  "ID":"Museum District",
  "Name":"Museum District"
 }
 ]
}
Run Code Online (Sandbox Code Playgroud)

Dou*_*las 46

您可以使用类似数组的语法访问该属性:

data[inputLocation]
Run Code Online (Sandbox Code Playgroud)

如果inputLocation设置为"Aspen",则它与这两行相同:

data["Aspen"]
data.Aspen
Run Code Online (Sandbox Code Playgroud)

  • 如果我们有动态位置怎么办?让我们看一下它可能是数据[名称] [年龄],其中名称和年龄都可以是动态的.在那种情况下我们该怎么办? (2认同)