Ad

Return Array For Specific Country In Json

- 1 answer

I tried to find a similar issue that I am having and haven't found it.

This is my json:

{
        "name": "United States",
        "code": "US",
        "label": "State",
        ...
        "province_codes": {
          "Alabama": "AL",
           "Alaska": "AK",
           "American Samoa": "AS",
           "Arizona": "AZ",
           "Arkansas": "AR",
           ...
        }
}

It's taken from this json repo https://raw.githubusercontent.com/JohnBendfeldt/country-province-data/master/countries.json

I'm trying to get the United States only and get the province_codes key and put into a new array for my react component. I've tried the below.

const states = [];
countryProvinceData.forEach(field => {
            if (field.name === "United States") {
                field.province_codes.map(code => {
                    states.push({
                        value: code, //Abbreviated state
                        label: code + " (" + code + ")" //full name and abbreviation in brackets
                    });
                });
            }
        });

        this.setState({ states });

But it's giving me this error: TypeError: field.province_codes.map is not a function

I hope someone can assist or give guidance.

Ad

Answer

province_codes is an object, but map is an Array prototype's function, in order to loop through object's keys you need to use either for in or Object.keys

Object.keys(field.province_codes).forEach(code => {
  states.push({
    value: code, //Abbreviated state
    label: code + " (" + field.province_codes[code] + ")" //full name and abbreviation in brackets
  });
})
Ad
source: stackoverflow.com
Ad