In my Typescript code, I am dealing with two arrays of objects. I need to find matches between the items in the first array and the second array. However, when there is no match, it returns an empty array:
Here is the first array:
let info = [
{
"brand": "bmw",
"year": "2020",
"country": "spain"
},
{
"brand": "ford",
"year": "2015",
"country": "italy"
},
{
"brand": "audi",
"year": "2010",
"country": "colombia"
}
]
This is the second array:
let dataInit = [
{
"brand": "bmw",
"year": "2020",
"wheel": 18
},
{
"brand": "audi",
"year": "2010",
"wheel": 17
}
]
To find the matches, I use the following approach:
info.forEach((itemInfo: any) => {
const { brand, year } = itemInfo
const result = dataInit.filter((itemInit: any) =>
brand.toUpperCase() === itemInit.brand.toUpperCase() && year.toUpperCase() === itemInit.year.toUpperCase()
)
const wheelRes = result[0].wheel;
console.log(result)
})
The above code snippet produces this output:
1. [{"brand": "bmw","year": "2020","wheel": 18}]
2. []
3. [{"brand": "audi","year": "2010","wheel": 17}]
When there is no match, an empty array is returned. Is there a way to have it return nothing instead?
My issue arises when trying to access the 'wheel' property from an empty array, resulting in the error message:
Error: Cannot read properties of undefined (reading 'wheel')