I am trying to filter JSON file with plain JavaScript.
city = await cities.filter(ea => {
return ea.city.toLowerCase().includes(searcher.value.toLowerCase()); //example value Belgrade
});
admin = await cities.filter(eb => {
return eb.admin_name.toLowerCase().includes(searcher.value.toLowerCase()); //example value Beograd
});
While filter that goes to city variable works perfect, one that goes to admin variable, witch is Copy-Paste of first one, return error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'toLowerCase')
and even if I remove toLowerCase function I get same error but (reading 'includes')
this is structure of JSON file:
[
{
"city": "Tokyo",
"city_ascii": "Tokyo",
"lat": 35.6839,
"lng": 139.7744,
"country": "Japan",
"iso2": "JP",
"iso3": "JPN",
"admin_name": "Tōkyō",
"capital": "primary",
"population": 39105000,
"id": 1392685764
},
]
CodePudding user response:
That just means admin_name
doesn't exist, or is null
/undefined
for at least one object of your array.
In order to support this, you could use optional chaining like this:
admin = cities.filter(eb => {
return eb.admin_name?.toLowerCase()?.includes(searcher.value.toLowerCase()); //example value Beograd
});
As a side note, await
ing a non Promise
value just returns that value, so it's useless in your case.