The file is as such
export const countries = [
{
alpha2: "TW",
alpha3: "TWN",
country: "Taiwan",
fifa: "TPE",
},
{
alpha2: "AF",
alpha3: "AFG",
country: "Afghanistan",
fifa: "AFG",
},
And I'm trying to do a lookup that matches with the countries and then return a specific object from said country, such as alpha3 string. For example, the country code I'm trying to search is Afghanistan, which should look into the Afghanistan object and return its country code that is alpha3 and return "AFG"
This is my code to search:
import { countries } from './countries'
const countryName = 'Afghanistan'
const countryCode = countries.find((obj) => {
if (obj.country === countryName) {
return obj.alpha3
}
})
CodePudding user response:
Since jolo's answer is not correct, this is what you need to do:
// return the object matching the condition
const matchingCountry = countries.find((obj) => obj.country === countryName)
// the use of the optional chaining operator protects you from accessing the alpha3 property is your find does not match any object
const matchingCountryCode = matchingCountry?.alpha3
And there you go! More on the optional chaining operator here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
CodePudding user response:
You're on the right track. 1 thing to note is that find()
returns an array item and not the property of an array item.
So just simplify yours steps:
- find array item
- get
alpha3
property on the array item you found
// countries.find() returns the array item
const matchingCountry = countries.find((obj) => {
if (obj.country === countryName) {
return obj;
}
})
// optional but advised: handle a situation where no country is found
if(!matchingCountry){
console.warn('no country found');
return; // this ensures no further code will be executed
}
// now you can safely assume matchingCountry is available
const matchingCountryCode = matchingCountry.alpha3;
console.log('success: ', matchingCountryCode)