More efficient way to extract address components

前端 未结 9 1148
再見小時候
再見小時候 2020-12-15 10:23

Currenty, I\'m using the following code to get the country, postal code, locality and sub-locality:

var country, postal_code, locality, sublocality;
for (i =         


        
9条回答
  •  时光取名叫无心
    2020-12-15 10:51

    My one-liner using a functional approach and map, filter, and ES2015:

    /**
     * Get the value for a given key in address_components
     * 
     * @param {Array} components address_components returned from Google maps autocomplete
     * @param type key for desired address component
     * @returns {String} value, if found, for given type (key)
     */
    function extractFromAddress(components, type) {
        return components.filter((component) => component.types.indexOf(type) === 0).map((item) => item.long_name).pop() || null;
    }
    

    Usage:

    const place = autocomplete.getPlace();
    const address_components = place["address_components"] || [];
    
    const postal_code = extractFromAddress(address_components, "postal_code");
    

提交回复
热议问题