[
{
"abbr": "AL",
"name": "Alabama",
"web": "www.google.com",
"capital": "Montgomery",
"lat": "32.361538",
"long": "-86.279118"
},
{
"abbr": "AK",
"name": "Alaska",
"capital": "Juneau",
"lat": "58.301935",
"long": "-134.419740"
},
{
"abbr": "AZ",
"name": "Arizona",
"capital": "Phoenix",
"lat": "33.448457",
"long": "-112.073844"
},
{
"abbr": "AR",
"name": "Arkansas",
"capital": "Little Rock",
"lat": "34.736009",
"long": "-92.331122"
},
// Additional state data here
]
My code retrieves data from a local JSON file without any errors, however when attempting to fetch data from an external URL, I encounter a "TypeError: states.filter is not a function" in my searchStates function. How can I successfully filter and manipulate data fetched from an external URL? Though I am able to log the content of the .json file retrieved from the external source using console.log, filtering the data is resulting in this error.
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
const searchStates = async searchText =>{
let url = 'https://exampleurl.json';
let res= await fetch(url);
let states= await res.json();
let matches=states.filter(state => {
const regex = new RegExp(`^${searchText}`,`gi`);
return state.name.match(regex) || state.abbr.match(regex);
});
if(searchText.length === 0){
matches=[];
matchList.innerHTML='';
}
outputHtml(matches);
};
const outputHtml = matches => {
if(matches.length > 0) {
const html=matches.map(match => `
<h4>${match.name} (${match.abbr}) <a href="https://${match.web}/">Visit example.com!</a></h4>
`).join('');
matchList.innerHTML = html;
}
}
search.addEventListener('input', () => searchStates(search.value));