I am working with an array of objects that contain content types
const contentTypes = [
{
"contentType": {
"content_type_id": 2,
"content_type": "image",
},
},
{
"contentType": {
"content_type_id": 3,
"content_type": "video",
},
},
{
"contentType": {
"content_type_id": 1,
"content_type": "audio",
},
},
]
In my function setType
, I aim to match elements and set the content_type_id
to content_type
. The values are then converted to strings.
const setType = (selectedType) => {
_setType(selectedType)
const typeString = contentTypes.find((item) => {
return item.contentType.content_type_id === selectedType
}).contentType.content_type;
onTypeChange(typeString)
}
The challenge arises when there is an element in the array contentTypes
missing the content_type_id
and content_type
, resulting in the error:
Unhandled Runtime Error TypeError: Cannot read property 'contentType' of undefined
You can view the code on jsFiddle here => https://jsfiddle.net/9x426Lv7/2/
How can I handle this scenario in the find method? Are there alternative approaches to address this issue?