get data from dynamic key value in json

AutoMEta picture AutoMEta · Oct 5, 2010 · Viewed 59k times · Source

The requirement is following:
I have to get the location field from page.

var input= global.input = document.getElementById("Location");

Get the neighborhood area from the json file based on input and show on the page.

I have a json object and have to filter the data from the json object based on the key value (location)

var inputLocation=input.value;

In my javascript I am getting the error if I use dynamic the key.

I am able to get the json array if I do this data.Aspen but i have to get the data from a text field and it can be different so if I call data.inputLocation... its coming undefined

when i use data.(inputLocation.value) getting the following error :

XML filter is applied to non-XML value ({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"
 }
 ]
}

Answer

Douglas picture Douglas · Oct 5, 2010

You can access the property using array-like syntax:

data[inputLocation]

If inputLocation is set to "Aspen", then it is the same as these two lines:

data["Aspen"]
data.Aspen