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.
CodePudding user response:
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