【发布时间】:2019-10-04 15:16:21
【问题描述】:
我有这个代码
const arr = [{
id: 1,
name: 'anything'
}, {
id: 2,
name: 'something'
}]
const target = [1]
我要查找target是否为1,我要name属性值
我会的
arr.find(o => target.includes(o.id)).name
但如果
arr.find(o => target.includes(o.id)) 没有name 属性,它会破坏整个应用程序并引发错误。
那么如何确保它不会崩溃呢?我可以这样做,但它很难看
const somethingValue = arr.find(o => target.includes(o.id)) && arr.find(o => target.includes(o.id)).name
或者我必须映射以确保 arr 始终具有 name 属性,如果 arr 是动态的并且南方来自外部方,我必须这样做。
还有什么办法可以解决吗?
【问题讨论】:
标签: javascript reactjs ecmascript-6