0

Need a little help. I have an array of properties that I filter on. However, if a property does not exist my view does not render because that properties becomes undefined. I need to gracefully ignore or show some other value.

export const countryList = [
    {name: 'France', flagCode: 'fr'},
    {name: 'England', flagCode: 'england'},
    {name: 'Germany', flagCode: 'gm'},
    {name: 'default', flagCode: 'default'},
];

const country = `${nationality}`
const flag = countryList.filter(function (el) {
    return el.name.toLowerCase() === country.toLowerCase();
})[0].flagCode;

So if ${nationality} returned "Italy", .flagCode would return undefined. I could add Italy to my array to solve this however there will be countries I miss and need a more graceful approached. So In my function I need to check if undefined, if it is then return a default name of 'default', if it does exist then return the value from the array. Thanks in advance.

Akhil Aravind
  • 5,741
  • 16
  • 35
Tom Rudge
  • 3,188
  • 8
  • 52
  • 94

3 Answers3

2

You can use an OR operator || to do this

const country = countryList.find(el => (el.name.toLowerCase() === country.toLowerCase());

const flag = (country && country.flagCode) || 'default';
Jee Mok
  • 6,157
  • 8
  • 47
  • 80
1

You can apply some to check existence first, if it's false, directly assign a default, else, run your filter code

let countryList = [
  {name: 'France', flagCode: 'fr'},
  {name: 'England', flagCode: 'england'},
  {name: 'Germany', flagCode: 'gm'},
  {name: 'default', flagCode: 'default'},
];

const country = `Italy`;
let flag = "";

if(countryList.some(x=>x.name === country)){
  flag = countryList.filter(function (el) {
       return el.name.toLowerCase() === country.toLowerCase();
     })[0].flagCode;
}else{
  flag = "default"
}

console.log(flag);
Isaac
  • 12,042
  • 16
  • 52
  • 116
1
const country = countryList.filter(function (el) {
    return el.name.toLowerCase() === country.toLowerCase();
})[0];

you can use default values

const flag = country.flagCode || 'default';

OR you can use ternary operators as well, which is again the same thing as above

const flag = !!country.flagCode ? country.flagCode : 'default';
Prasanna
  • 4,125
  • 18
  • 41