Reputation: 339
I want to check if a value exists in an array of objects.
My array looks something like this:
[
0: {
id: 'unique_obj_id',
item: {
id: 'unique_item_id',
...
},
...
},
1: {...}
]
The objects in the array can be one of many interface types (depending on my api call, here: resource
strings represent these interfaces, which are defined somewhere else). But one array will always consist of the same interface types for a given data request.
I'm trying to write a reusable function to check whether given_id
exists for any object in the array for obj.item.id
.
So far I've managed to write the correct logic but typescript throws some exceptions that I can't seem to figure out. shopApprovalData
is a collection of interfaces each following the above object structure accessible by the indices of resource
.
export type ApprovalResource = 'str1' | 'str2' | 'str3' | 'str4' | 'str5';
export const checkApprovalItem = (given_id: string, resource: ApprovalResource) => {
const shopApprovalData = useShopApprovals();
if (shopApprovalData && shopApprovalData[resource]) {
const resourceApprovalData = shopApprovalData[resource];
if (resourceApprovalData.find(e => e.item.id === id)) {
return true;
}
}
return false;
}
Typescript shows me that shopApprovalData
and itemApprovalData
is possibly undefined and that the expression find()
is not callable since signatures of members of the union type are not compatible with each other. (Apparently, some
removes the error, why?)
What approach should I choose instead to check whether the given_id
exists in any object of the array?
Upvotes: 2
Views: 667
Reputation: 453
Based on your usecase, i create this code sandbox: https://codesandbox.io/s/stackoverflow-answer-ke9drk?file=/src/index.ts
explanation:
Type
wont compile, so we need something to mark what the interface of the object.Also i may confused by your code shopApprovalData[resource]
what do you want to achieve here? for example, if resource
is str1
shopApprovalData[resource]
will always return undefined
because no index str1
in Array
I hope it help, Best Regards
Upvotes: 1