I have two arrays of objects in Typescript, I am going through the first array to get the matches of the second array, my problem is that if it doesn’t match it returns an empty array:
This 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
}
]
This is what I do to get the matches:
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)
})
This is what it returns:
1. [{"brand": "bmw","year": "2020","wheel": 18}]
2. []
3. [{"brand": "audi","year": "2010","wheel": 17}]
Finding no match returns [], is it possible to return nothing?
This is my problem:
I want to get the value of the ‘wheel’ property, but when an empty array comes I get an error: Error: Cannot read properties of undefined (reading 'wheel')
2
Answers
You can just check if the array is empty before accessing it.
Of course, just use
null
instead of the empty array. However, that won’t solve this problem:It would just replace that error with a new error, and for the same reason.
Instead, check the length of the array before trying to use it. For example:
Alternatively… from the use of
result[0]
(hard-coded first array element) it seems like you only ever expect one element to be found by thefilter
operation. If that’s the case then you can usefind
instead:If no match is found then
find
will returnundefined
, which you can check the same way: