2015-10-18 54 views
0

我想根據用戶插入的郵政編碼自動填充城市和州的值。我無法將輸入的郵政編碼與json對象中提供的郵政編碼進行比較。 OBJ長度的值是1,它必須是3obj的長度爲1 - javascript

var text = '{"zipcodes":[' + 
'{"zip":"22031","city":"Fairfax" ,"State":"VA" },' + 
'{"zip":"22032","city":"AshBurn" ,"State":"VA" },' + 
'{"zip":"22033","city":"Tysons" ,"State":"VA" }]}'; 

var obj = JSON.parse(text); 
var n = Object.keys(obj).length; 

for(i=0; i<=n; i++){ 

    if(obj.zipcodes[i].zip.parseInt() == zipcodes.parseInt()){ 

     document.getElementById("city").value = obj.zipcodes[i].city; 
     document.getElementById("state").value = obj.zipcodes[i].State; 

    } 
} 
+0

有一個在'obj'只需一個鍵, 'obj.zipcodes',這是一個數組,你可以用'for'循環來循環。 – Teemu

回答

2

目的解析後變爲:

{ 
    "zipcodes":[ 
    {"zip":"22031","city":"Fairfax" ,"State":"VA" }, 
    {"zip":"22032","city":"AshBurn" ,"State":"VA" }, 
    {"zip":"22033","city":"Tysons" ,"State":"VA" }]} 
    ] 
}; 

所以對象的鍵數爲1,其爲郵編。如果你想算的郵編,

使用此:

var obj = JSON.parse(text); 
var n = obj.zipcodes.length; 
0

沒有嘗試過的代碼,但看起來像你真的只是得到了對象,這就是「郵編」 1個鍵。

我想你應該通過obj ['zipcodes']來代替循環嗎?

0

是的,這的確是長度爲1 如果你想通過郵政編碼,然後重複對於給定的片段上方我只是這樣做:

var n = obj.zipcodes.length; 
//continue your computation here.