Ad
Return Array For Specific Country In Json
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad