2013-06-19 79 views
-1

我有一個json,我想根據「區域」字段進行解析,以便通過選擇輸入來獲取區域列表等。根據動態值解析json

var data = { 
    "zone01": [{ 
     "region": "North", 
     "state": "New York", 
     "county": "Albany", 
     "code": "01" 
    }, { 
     "region": "North", 
     "state": "New York", 
     "county": "Albany", 
     "code": "05" 
    }, { 
     "region": "North", 
     "state": "Maine", 
     "county": "Auburn", 
     "code": "07" 
    }], 
    "zone02": [{ 
     "region": "South", 
     "state": "Florida", 
     "county": "Gainseville", 
     "code": "82" 
    }, { 
     "region": "South", 
     "state": "Florida", 
     "county": "Macclenny", 
     "code": "73" 
    }] 
}; 

我可以通過分析它:

function setValues(range, zone, region, state, country){ 
    if(range === 'zone'){ 
     var getRegions = _.groupBy(data.zone02, 'region'); 
     $.each(getRegions, function(k, v){ 
      var region = JSON.stringify(k); 
      region = region.replace(/"/g,''); 
      $('select#region').append('<option value="'+region+'">'+region+'</option>'); 
     }); 
    } 
} 

但我真正需要的是_.groupBy(data.zone02, '區域')與data.zone02是數據+函數的變量

UPDATE

這裏是我的成品,SANS可讀性和再可用性:jsFiddle

+1

您的意思是'var getRegions = _.groupBy(data [zone],'region');'? – Jay

+0

是的 - 但不要告訴任何人。我之前嘗試過,它說不,但我認爲我可能把自引['blush'] – jbolanos

+1

這不是解析JSON,它只是訪問對象中的屬性。 – Barmar

回答

1

使用括號表示法來引用使用變量的屬性。

data[zone]