You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在含嵌套数组的JavaScript对象中搜索值并返回对应键

解决嵌套对象中搜索数字返回对应键的问题

嘿,我明白你遇到的麻烦了!你的对象里每个键对应的都是多层嵌套数组,之前的循环可能没处理好这种嵌套结构,导致没找到正确的结果。别担心,我给你两种可行的解决方案,直接就能用~

首先明确目标:遍历对象的每个键,检查该键对应的二维数组里是否包含用户输入的数字,找到第一个匹配的键就返回它。

方法一:基础循环遍历(适合理解原理)

这种写法一步步拆解嵌套结构,新手也能看懂逻辑:

var list = { nums: [ [117], [108] ], numsset: [ [2256, 2265], [234], [3445, 3442] ] };

function findMatchingKey(targetNum) {
  // 遍历对象的每一个键
  for (const key in list) {
    // 遍历当前键对应的外层数组
    const outerArr = list[key];
    for (let i = 0; i < outerArr.length; i++) {
      const innerArr = outerArr[i];
      // 遍历内层数组的每一个元素
      for (let j = 0; j < innerArr.length; j++) {
        if (innerArr[j] === targetNum) {
          // 找到匹配值,直接返回当前键
          return key;
        }
      }
    }
  }
  // 如果遍历完都没找到,返回null或者提示信息
  return null;
}

// 测试一下:
console.log(findMatchingKey(108)); // 输出 "nums"
console.log(findMatchingKey(3445)); // 输出 "numsset"
console.log(findMatchingKey(2265)); // 输出 "numsset"

方法二:用数组方法简化代码(更简洁)

利用JavaScript的Object.entries()、some()和includes()方法,可以把代码写得更简洁,逻辑也清晰:

var list = { nums: [ [117], [108] ], numsset: [ [2256, 2265], [234], [3445, 3442] ] };

function findMatchingKey(targetNum) {
  // 把对象转换成键值对数组,遍历每一组
  for (const [key, arr] of Object.entries(list)) {
    // 检查外层数组里是否有任意一个子数组包含目标数字
    const hasMatch = arr.some(subArray => subArray.includes(targetNum));
    if (hasMatch) {
      return key;
    }
  }
  return null;
}

// 测试效果和上面完全一样
console.log(findMatchingKey(108)); // "nums"
console.log(findMatchingKey(3445)); // "numsset"

结合页面输入框使用

要把这个功能和页面的输入框结合起来,只需要监听输入事件,获取用户输入的数字后调用函数即可:

// 获取页面上的输入框元素(假设输入框的id是"numberInput")
const inputBox = document.getElementById('numberInput');

inputBox.addEventListener('input', function() {
  // 把输入的字符串转成数字
  const inputNum = Number(this.value);
  // 排除非数字的情况
  if (!isNaN(inputNum)) {
    const resultKey = findMatchingKey(inputNum);
    // 把结果展示出来,比如用alert或者插入到页面某个元素里
    alert(resultKey ? `匹配的键是:${resultKey}` : '没有找到对应的键哦');
  }
});

这样用户输入数字后,就能立刻得到对应的键啦~

内容的提问来源于stack exchange,提问作者Tony Hensler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:10:39