React Javascript,在数组undefined中查找并跳过
React Javascript, find in a array undefined and skip it
我有一个对象数组
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",
},
},
]
这是我的函数 setType
,我可以在其中找到任何元素并将 content_type_id
设置为 content_type
。我将值转换为字符串
const setType = (selectedType) => {
_setType(selectedType)
const typeString = contentTypes.find((item) => {
return item.contentType.content_type_id === selectedType
}).contentType.content_type;
onTypeChange(typeString)
}
我的问题是我在数组 contentTypes
中也有一个元素没有 content_type_id
和 content_type
所以我得到这个错误
未处理的运行时错误
类型错误:无法读取未定义的 属性 'contentType'
这是一个 jsFiddle => https://jsfiddle.net/9x426Lv7/2/
如何在查找方法中跳过这个元素?有更好的方法吗?
显然您的查找函数未获取任何值并返回未定义,请检查您要查找的所选类型是否确实存在
考拉7,你可以试试这个
const setType = (selectedType) => {
_setType(selectedType)
let typeString = contentTypes.find((item) => {
return item.contentType.content_type_id === selectedType
})
typeString = typeString ? typeString.contentType.content_type : null; // null or give it another default value
onTypeChange(typeString)
}
怎么样?
const setType = (selectedType) => {
const typeString = contentTypes.find((item) => {
return item.contentType.content_type_id === selectedType
})
if(typeString) {
return contentType.content_type;
}
return null;
}
我有一个对象数组
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",
},
},
]
这是我的函数 setType
,我可以在其中找到任何元素并将 content_type_id
设置为 content_type
。我将值转换为字符串
const setType = (selectedType) => {
_setType(selectedType)
const typeString = contentTypes.find((item) => {
return item.contentType.content_type_id === selectedType
}).contentType.content_type;
onTypeChange(typeString)
}
我的问题是我在数组 contentTypes
中也有一个元素没有 content_type_id
和 content_type
所以我得到这个错误
未处理的运行时错误 类型错误:无法读取未定义的 属性 'contentType'
这是一个 jsFiddle => https://jsfiddle.net/9x426Lv7/2/
如何在查找方法中跳过这个元素?有更好的方法吗?
显然您的查找函数未获取任何值并返回未定义,请检查您要查找的所选类型是否确实存在
考拉7,你可以试试这个
const setType = (selectedType) => {
_setType(selectedType)
let typeString = contentTypes.find((item) => {
return item.contentType.content_type_id === selectedType
})
typeString = typeString ? typeString.contentType.content_type : null; // null or give it another default value
onTypeChange(typeString)
}
怎么样?
const setType = (selectedType) => {
const typeString = contentTypes.find((item) => {
return item.contentType.content_type_id === selectedType
})
if(typeString) {
return contentType.content_type;
}
return null;
}