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.

4
  • 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). Commented Mar 22, 2021 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? Commented Mar 22, 2021 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. Commented Mar 22, 2021 at 12:01
  • @er-sho : Yeah, I am trying to figure what to do if the number of countries grow. Commented Mar 22, 2021 at 12:04

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.