-1

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.

designtocode
  • 2,215
  • 4
  • 21
  • 35

1 Answers1

2

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
  });
})
Liad Yogev
  • 854
  • 7
  • 16
  • 1
    Thank you for the direction. Was confused why it was returning that error and it was missing `Object.keys`. Been a long day! – designtocode Nov 14 '19 at 11:43