如何通过忽略具有未定义属性的元素来过滤数组?
How to filter an array by ignoring elements with undefined properties?
我正在尝试将图像 URL 映射到头像组件。我使用的数据来自 Google 本书 API。数据资源是一组对象(书籍)。某些对象缺少我定位的 "thumbnail" 字段的值。
如果这些对象没有 "thumbnail" 的值,我想忽略它们并继续通过数组进行映射。
我正在使用 React Native 和 Expo
我已经尝试过 Stack Overflow 上提到的各种方法,包括 array.filter(),在 array.map() 之前对我的数据进行逻辑处理。 None 的推荐解决方案有效。
我收到的错误是:
TypeError: TypeError: undefined is not an object(evaluating 'url.volumeInfo.imageLink.thumbnail')
看来我什至不能在 "if" 语句中包含该路径,这对我来说很奇怪 - 因为即使该值未定义,那又有什么关系呢?
renderCategory() {
if (this.props.adventure.payload[0]) {
const fetched_Book = this.props.adventure.payload;
const filteredThumbnails = fetched_Book.filter(url =>{
// The console log below shows 4 urls before it fails)
console.log('URL', url.volumeInfo.imageLinks.thumbnail)
if(typeof url.volumeInfo.imageLinks.thumbnail === "undefined"){
return false
}
else return true;
})
const allThumbnails= filteredThumbnails.map(book => book.volumeInfo.imageLinks.thumbnail);
return (
<>
<View style={styles.thumbnailContainer}>
{
allThumbnails.map((l, i) =>
<Avatar
key={i}
size="large"
source={{ uri: l }}
style={styles.thumbNail}
onPress={() => this.onSelectedBook(fetched_Book, i)}
/>
)
}
</View>
</>
)
}
else return ''
}
预期的输出是经过过滤的新对象数组,然后可以将其映射到我的头像组件中。
此错误意味着缩略图路径的某些部分不存在,因此您需要检查该路径的每个部分是否存在:
const filteredThumbnails = fetched_Book
.filter(url => !!url && !!url.volumeInfo && !!url.volumeInfo.imageLinks && typeof url.volumeInfo.imageLinks.thumbnail === 'undefined')
我正在尝试将图像 URL 映射到头像组件。我使用的数据来自 Google 本书 API。数据资源是一组对象(书籍)。某些对象缺少我定位的 "thumbnail" 字段的值。
如果这些对象没有 "thumbnail" 的值,我想忽略它们并继续通过数组进行映射。
我正在使用 React Native 和 Expo
我已经尝试过 Stack Overflow 上提到的各种方法,包括 array.filter(),在 array.map() 之前对我的数据进行逻辑处理。 None 的推荐解决方案有效。
我收到的错误是:
TypeError: TypeError: undefined is not an object(evaluating 'url.volumeInfo.imageLink.thumbnail')
看来我什至不能在 "if" 语句中包含该路径,这对我来说很奇怪 - 因为即使该值未定义,那又有什么关系呢?
renderCategory() {
if (this.props.adventure.payload[0]) {
const fetched_Book = this.props.adventure.payload;
const filteredThumbnails = fetched_Book.filter(url =>{
// The console log below shows 4 urls before it fails)
console.log('URL', url.volumeInfo.imageLinks.thumbnail)
if(typeof url.volumeInfo.imageLinks.thumbnail === "undefined"){
return false
}
else return true;
})
const allThumbnails= filteredThumbnails.map(book => book.volumeInfo.imageLinks.thumbnail);
return (
<>
<View style={styles.thumbnailContainer}>
{
allThumbnails.map((l, i) =>
<Avatar
key={i}
size="large"
source={{ uri: l }}
style={styles.thumbNail}
onPress={() => this.onSelectedBook(fetched_Book, i)}
/>
)
}
</View>
</>
)
}
else return ''
}
预期的输出是经过过滤的新对象数组,然后可以将其映射到我的头像组件中。
此错误意味着缩略图路径的某些部分不存在,因此您需要检查该路径的每个部分是否存在:
const filteredThumbnails = fetched_Book
.filter(url => !!url && !!url.volumeInfo && !!url.volumeInfo.imageLinks && typeof url.volumeInfo.imageLinks.thumbnail === 'undefined')