map中用find时出现Cannot read properties of undefined(reading code)错误
为什么会出现“Cannot read properties of undefined(reading code)”错误?
这个错误的核心是你尝试访问一个undefined值的code属性,结合你的代码,可能有两种触发场景:
someItems.otherItems数组里存在undefined元素:当map遍历到这类元素时,otherItem是undefined,访问otherItem.code就会抛出这个错误。completelyDifferentItems数组里存在undefined元素:find方法遍历到这类元素时,differentItem是undefined,访问differentItem.code同样会触发错误。
解决办法
针对第一种场景,可以先过滤掉数组里的undefined元素,或者用可选链运算符做安全访问:
// 方式1:过滤掉undefined元素再处理 const updatedMenuItems = someItems.otherItems.filter(Boolean).map(otherItem => { const existItem = completelyDifferentItems.find(differentItem => differentItem.code === otherItem.code) if (existItem) { otherItem.someKey = existItem.someKey } return otherItem }) // 方式2:用可选链做安全访问 const updatedMenuItems = someItems.otherItems.map(otherItem => { const existItem = completelyDifferentItems.find(differentItem => differentItem?.code === otherItem?.code) if (existItem) { otherItem.someKey = existItem.someKey } return otherItem })
针对第二种场景,提前清理无效元素或者同样用可选链:
// 方式1:提前过滤掉completelyDifferentItems里的undefined元素 const validDifferentItems = completelyDifferentItems.filter(Boolean) const updatedMenuItems = someItems.otherItems.map(otherItem => { const existItem = validDifferentItems.find(differentItem => differentItem.code === otherItem.code) if (existItem) { otherItem.someKey = existItem.someKey } return otherItem }) // 方式2:用可选链做安全访问 const updatedMenuItems = someItems.otherItems.map(otherItem => { const existItem = completelyDifferentItems.find(differentItem => differentItem?.code === otherItem.code) if (existItem) { otherItem.someKey = existItem.someKey } return otherItem })
内容的提问来源于stack exchange,提问作者Serdar Sarıtaş
相关产品推荐
相关产品推荐

