JavaScript如何检查数组b的myPointID是否存在于嵌套对象数组a中
错误原因
- 数组
a是外层结构,本身不包含points属性,points是a数组每个元素下的子属性,需要先遍历a的所有元素才能访问到 - 数组
b也是对象集合,不是单个对象,不能直接取b.myPointID,需要先批量提取b中所有的myPointID用于匹配
实现代码
建议先把需要匹配的ID存入Set结构,相比数组includes匹配性能更高,尤其数据量大的时候优势明显:
场景1:判断b中的myPointID是否有至少一个存在于a中
// 提取b所有myPointID const bIdSet = new Set(b.map(item => item.myPointID)) // 双层some匹配,找到符合项就终止遍历,性能最优 const hasMatch = a.some(aItem => { return aItem.points.some(point => bIdSet.has(point.myPoint.myPointID)) }) console.log(hasMatch) // 示例数据下输出true
场景2:提取a中所有匹配的points记录
const bIdSet = new Set(b.map(item => item.myPointID)) // flatMap直接拍平嵌套的points数组,返回所有匹配项 const matchedList = a.flatMap(aItem => { return aItem.points.filter(point => bIdSet.has(point.myPoint.myPointID)) }) console.log(matchedList)
场景3:为b中每个元素标记其myPointID是否在a中存在
// 先提取a中所有myPointID const aIdSet = new Set(a.flatMap(aItem => aItem.points.map(p => p.myPoint.myPointID))) const bWithFlag = b.map(item => ({ ...item, isExistInA: aIdSet.has(item.myPointID) })) console.log(bWithFlag)
内容的提问来源于stack exchange,提问作者haydnD
相关产品推荐
相关产品推荐

