如何搜索二维对象数组并返回目标值所在的索引?
如何在二维对象数组中查找指定值的索引位置
核心思路
通过双重遍历实现:先遍历二维数组的每个子数组(记录外层索引),再遍历子数组内的每个对象(记录内层索引),逐一检查对象是否包含目标键且对应值匹配。找到匹配项时返回格式化的索引(如(1,2)),遍历结束未找到则返回null(或对应语言的空值)。
JavaScript 实现示例
function findTargetIndex(twoDArray, targetKey, targetValue) { // 遍历外层数组,记录行索引 for (let outerIdx = 0; outerIdx < twoDArray.length; outerIdx++) { const subArray = twoDArray[outerIdx]; // 遍历子数组内的对象,记录列索引 for (let innerIdx = 0; innerIdx < subArray.length; innerIdx++) { const currentObj = subArray[innerIdx]; // 检查对象的目标键值是否匹配 if (currentObj[targetKey] === targetValue) { return `(${outerIdx}, ${innerIdx})`; } } } // 未找到匹配项返回null return null; } // 测试用例 const DB = [ [{venue_city: "London"}, {venue_city: "Paris"}], [{venue_city: "New York"}, {venue_city: "Tokyo"}, {venue_city: "Rio"}], [{venue_city: "Sydney"}] ]; console.log(findTargetIndex(DB, "venue_city", "Rio")); // 输出:(1,2) console.log(findTargetIndex(DB, "venue_city", "Berlin")); // 输出:null
Python 实现示例
def find_target_index(two_d_array, target_key, target_value): # 遍历外层数组,enumerate同时获取索引和子数组 for outer_idx, sub_array in enumerate(two_d_array): # 遍历子数组内的对象 for inner_idx, current_obj in enumerate(sub_array): # 用get避免键不存在报错,同时检查值匹配 if current_obj.get(target_key) == target_value: return f"({outer_idx}, {inner_idx})" # 未找到返回None return None # 测试用例 DB = [ [{"venue_city": "London"}, {"venue_city": "Paris"}], [{"venue_city": "New York"}, {"venue_city": "Tokyo"}, {"venue_city": "Rio"}], [{"venue_city": "Sydney"}] ] print(find_target_index(DB, "venue_city", "Rio")) # 输出:(1,2) print(find_target_index(DB, "venue_city", "Berlin")) # 输出:None
注意事项
- 如果需要返回数组格式的索引(如
[1,2]),直接修改返回值为[outerIdx, innerIdx]即可,无需字符串格式化。 - 若存在多个匹配项,上述代码会返回第一个匹配项的索引;如果需要返回所有匹配索引,可改为收集结果到数组中再返回。
内容的提问来源于stack exchange,提问作者Powl_London
相关产品推荐
相关产品推荐

