如何在数组中根据指定Uid值查找并获取对应的完整对象
数组Uid匹配判断与对象获取方案
首先给定的目标数组和待匹配Uid如下:
const targetArr = [ { "Name":"S", "Level":"1", "Uid":"huybd776", "isHuman":false }, { "Name":"R", "Level":"35", "Uid":"673bjhbjhdcsy", "isHuman":true } ] const searchUid = "673bjhbjhdcsy"
方法1:使用Array.find()(常规场景首选)
该方法会遍历数组返回第一个满足匹配条件的元素,无匹配项时返回undefined,可同时完成存在性判断和对象获取:
const matchedObj = targetArr.find(item => item.Uid === searchUid) if (matchedObj) { // Uid存在,可直接使用matchedObj操作完整对象 console.log("匹配到的对象:", matchedObj) } else { console.log("当前Uid不存在于数组中") }
特点:
- 代码简洁,匹配到结果后立即停止遍历,性能损耗低
- 仅返回第一个匹配的元素,适配Uid唯一的通用场景
注意:如果数组允许存在null元素,判断条件需调整为if (matchedObj !== undefined),避免误判
方法2:使用Array.filter()(多匹配场景适用)
如果数组可能存在多个相同Uid的元素,可使用该方法返回所有匹配项组成的数组:
const matchedObjList = targetArr.filter(item => item.Uid === searchUid) if (matchedObjList.length > 0) { console.log(`共找到${matchedObjList.length}个匹配对象:`, matchedObjList) } else { console.log("当前Uid不存在于数组中") }
特点:
- 可获取所有匹配的元素,适合Uid不唯一的特殊场景
- 会完整遍历整个数组,数据量较大时性能弱于
find()方法
方法3:基础for循环(兼容旧环境)
如果需要兼容不支持ES6语法的极低版本运行环境,可使用基础遍历实现:
let matchedObj = null for (let i = 0; i < targetArr.length; i++) { if (targetArr[i].Uid === searchUid) { matchedObj = targetArr[i] break // 匹配到后立即跳出循环,减少性能损耗 } } if (matchedObj) { console.log("匹配到的对象:", matchedObj) } else { console.log("当前Uid不存在于数组中") }
内容的提问来源于stack exchange,提问作者Sai Krishnadas
相关产品推荐
相关产品推荐

