2016-07-11 61 views
0

使用Google的Maps API,我希望能夠通過同一對象內的數組內的值找到對象內的鍵的值。當我爲了查看控制檯我頁上的「檢查元素」,這裏是它顯示在對象結構方面:使用數組值查找父對象的鍵值

results: { 
    address_components [ 
     0: Object: { 
      long_name: "704", 
      short_name: "704", 
      types [ 
       0:"street_number" 
      ] 
     } 
     1: Object {...} 
     2: Object {...} 
     3: Object {...} 
    ] 
    place_id:"8AS8D8F8A881C81DA6S6D8" 
} 

我希望能夠找到「street_number」的對象,以便我可以找到也存在於對象中的相應的「704」值。

棘手的部分是,「address_compenents」內的值不總是在相同的順序,所以我不能只寫在我的JavaScript的results[0].address_components[0].long_name找到它。我被限制在這個項目中的JavaScript,所以任何在該語言的答案將不勝感激。先謝謝你!

注:我不反對使用庫如lodash或下劃線,如果它有助於解決問題。

+0

相關的問題:[反向地理編碼示例中不顯示位置的街道名稱某些地區](http://stackoverflow.com/questions/33656636/reverse-geocoding-example-doesnt-display-the-street-name-of-a-location-in-some) – geocodezip

+0

相關問題:[Google地圖:如何獲得國家,州/省/地區,具有經濟/長期價值的城市?](http:// s tackoverflow.com/questions/4013606/google-maps-how-to-get-country-state-province-region-city-given-a-lat-long-va) – geocodezip

回答

1

第一個find()該項目,然後閱讀所需的屬性。

請注意,您還應該考慮並處理響應中沒有street_number的情況,此代碼段未涵蓋此情況。

var results = { 
 
    address_components: [{ 
 
    long_name: "704", 
 
    short_name: "704", 
 
    types: [ 
 
     "street_number" 
 
    ] 
 
    }, { 
 
    long_name: "100", 
 
    short_name: "100", 
 
    types: [ 
 
     "attribute_a" 
 
    ] 
 
    }, { 
 
    long_name: "200", 
 
    short_name: "200", 
 
    types: [ 
 
     "attribute_b" 
 
    ] 
 
    }, { 
 
    long_name: "300", 
 
    short_name: "300", 
 
    types: [ 
 
     "attribute_c" 
 
    ] 
 
    }], 
 
    place_id: "8AS8D8F8A881C81DA6S6D8" 
 
} 
 

 
var streetNumber = results.address_components.find(function(item) { 
 
    return item.types.some(function(subitem) { 
 
    return subitem === 'street_number' 
 
    }); 
 
}).long_name; 
 

 
console.log(streetNumber); // 704

+0

感謝您的及時迴應!然而,我碰巧遇到了其他地方的答案,然而,你的答案也能解決我的問題。謝謝! – Austin

0

有可能通過使用Array.filter()來做到這一點

results: { 
    address_components [ 
     0: Object: { 
      long_name: "704", 
      short_name: "704", 
      types [ 
       0:"street_number" 
      ] 
     } 
     1: Object {...} 
     2: Object {...} 
     3: Object {...} 
    ] 
    place_id:"8AS8D8F8A881C81DA6S6D8" 
} 


const result = results.address_components.find(item => item.types.indexOf('street_number') > -1) 

const longName = result.long_name // 704 
const shortName = result.short_name // 704