如何根据前两个字段值查找字典数组的第三个元素及索引
根据字典数组的双字段匹配,获取目标值与元素索引
针对你给出的场景,我整理了两种实用的JavaScript实现方案,能快速定位到符合name和game条件的元素,同时拿到它的number值和在数组中的索引:
方案一:用findIndex快速定位索引
这种方式逻辑直观,先找到匹配元素的索引,再通过索引提取对应值:
const dict = [ {"name": "A", "game": "X", "number": 5}, {"name": "B", "game": "X", "number": 3}, {"name": "A", "game": "Y", "number": 1}, {"name": "C", "game": "Z", "number": 2} ]; // 定义要匹配的目标条件 const targetName = "A"; const targetGame = "X"; // 获取匹配元素的索引(找不到时返回-1) const matchedIndex = dict.findIndex(item => item.name === targetName && item.game === targetGame); // 安全获取对应的number值 const matchedNumber = matchedIndex !== -1 ? dict[matchedIndex].number : null; console.log(`匹配元素的索引:${matchedIndex},对应的number值:${matchedNumber}`); // 输出结果:匹配元素的索引:0,对应的number值:5
方案二:单次遍历同时获取索引与值
如果想减少一次数组访问,也可以用forEach在一次遍历中完成所有操作,还能提前终止循环优化性能:
const dict = [ {"name": "A", "game": "X", "number": 5}, {"name": "B", "game": "X", "number": 3}, {"name": "A", "game": "Y", "number": 1}, {"name": "C", "game": "Z", "number": 2} ]; const targetName = "A"; const targetGame = "X"; let matchedIndex = -1; let matchedNumber = null; dict.forEach((item, index) => { if (item.name === targetName && item.game === targetGame) { matchedIndex = index; matchedNumber = item.number; // 找到第一个匹配项后直接终止循环 return; } }); console.log(`匹配元素的索引:${matchedIndex},对应的number值:${matchedNumber}`); // 输出结果:匹配元素的索引:0,对应的number值:5
额外提示
- 以上两种方案都会返回第一个匹配的元素,如果你的数组存在多个符合条件的元素,想要收集所有匹配项的索引和值,可以用
filter结合map来实现。 - 一定要记得判断
matchedIndex是否为-1,避免出现数组越界的错误(当没有找到任何匹配项时)。
内容的提问来源于stack exchange,提问作者Yamika Izumi
相关产品推荐
相关产品推荐

