-1

I have a Typescript project with an array and a JSON object. What I do is take the value of a property of the object, where the value of the other property is in the array.

This is the array:

let country: string[] = [ 'AR', 'ES'];

This is the object:

let objJson = [
  {
    "codCountry": "AR",
    "desCountry": "ARGENTINA"
  },
  {
    "codCountry": "CO",
    "desCountry": "COLOMBIA"
  },
  {
    "codCountry": "ES",
    "desCountry": "SPAIN"
  }];

This is the loop:

for (let getO of objJson) {
    for (let getC of country) {
      if (getO.codCountry == getC) {
        console.log(getO.desCountry)
      }
    }
  }

This is what I get:

> ARGENTINA
> SPAIN

My problem is: is there any way to improve this to avoid the need to iterate twice? In this example the arrays are small but I imagine that if they are larger this process would take a long time, I would like to know what is the most efficient way to do it. this.

menphis
  • 85
  • 1
  • 8
  • https://stackoverflow.com/questions/60339931/checking-if-an-array-of-objects-contains-value-without-looping – Awais Khan Oct 24 '21 at 10:33

1 Answers1

1

In the first loop use country.includes(getO.codCountry) so the code reduces to

for (let getO of objJson){
    if (country.includes(getO.codCountry))
        console.log(getO.desCountry)
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

nobody
  • 26
  • 1