0

I have an interface Country as below in my component.ts class :

export interface Country{
  id: String;
  name: String;
  checked: false; 
}

const country: Country[] = [

   { id: 'India', name: 'India', checked: false},
   { id: 'USA', name: 'USA', checked: false},
   { id: 'Canada', name: 'Canada', checked: false},

]

selectedCountry: Country[] ;

On UI I have checkboxes for respective countries.

Let's say if user selects India/USA/Canada ( one at a time). So to handle the same, I am trying to write an if-else statement as :

if(this.selectedCountry.includes('India')
 // do something;
else if(this.selectedCountry.includes('USA')
 // do something;
else ...  

But I am getting an error : Argument of type 'string' is not assignable to parameter of type 'Country'.

Can someone help me out figure the issue. Any help/pointers are highly appreciable.

Amit kumar
  • 2,169
  • 10
  • 25
  • 36
  • `this.selectedCountry` contains `Country` objects, not strings. You need to check if a field of the objects matches that (not sure i you want `id` or `name`). – VLAZ Mar 22 '21 at 12:00
  • Does this answer your question? [How to determine if Javascript array contains an object with an attribute that equals a given value?](https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e) – VLAZ Mar 22 '21 at 12:00
  • 1
    What about if your contry array contains 100 countries, Are you going to code if-else for 100 times? I think this will not good solution. – er-sho Mar 22 '21 at 12:01
  • @er-sho : Yeah, I am trying to figure what to do if the number of countries grow. – Amit kumar Mar 22 '21 at 12:04

2 Answers2

3

Try this

this.selectedCountry.some(c => c.name === "India");

The some() method checks if any of the elements in an array pass a test (provided as a function).

For reusable code :

checkCountry(name: string): boolean{
  return this.selectedCountry.some(c => c.name === name);
}
tmsbrndz
  • 1,297
  • 2
  • 9
  • 23
1

Is this.selectedCountry Object country?. How about this.selectedCountry.id.includes('India') ?

Ian Cho
  • 89
  • 6