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

如何过滤嵌套数组对象?匹配指定key值返回dropDownTwo数组

过滤嵌套数组对象,匹配指定key后返回对应数组

问题说明

给定嵌套数组nestedArray和匹配值testName,需要找到所有dropDownOne.key等于testName的对象,返回其对应的dropDownTwo数组。

示例数据

let testName = 'filterValue'

var nestedArray =  [
      [
          {
              dropDownOne: {
                  key: "filterValue",
                  value: "test1"
              },
              dropDownTwo: [
                  {
                      key: "retrieveArrKey1",
                      value: "test123"
                  },
                  {
                      key: "retrieveArrKey2",
                      value: "test345"
                  }
              ]
          }
      ],
      [
          {
              dropDownOne: {
                  key: "NoFilter",
                  value: "test2"
              },
              dropDownTwo: [
                  {
                      key: "dropDown2",
                      value: "test"
                  },
                  {
                      key: "dropDown3",
                      value: "test"
                  }
              ]
          }
      ]
    ]

期望输出

[
    {
        key: "retrieveArrKey1",
        value: "test123"
    },
    {
        key: "retrieveArrKey2",
        value: "test345"
    }
]

现有代码问题分析

你写的代码存在以下问题:

  • 嵌套filter逻辑错误:外层filter遍历的是nestedArray的子数组,内层filter完全没必要,且错误访问value[0](子数组里的元素是单个对象,并非数组)
  • 返回值逻辑混乱:没有正确提取目标对象的dropDownTwo属性,反而返回了无关的数组项

正确解法

解法1:扁平化数组后查找

先把二维嵌套数组扁平化,再用find定位匹配对象,最后提取目标数组:

// 扁平化二维数组
const flattened = nestedArray.flat();
// 找到匹配的对象(注意去除testName的多余空格)
const targetObj = flattened.find(item => item.dropDownOne.key === testName.trim());
// 处理未找到匹配项的情况
const result = targetObj ? targetObj.dropDownTwo : [];
console.log(result);

解法2:嵌套遍历查找

如果不想使用flat(),可以直接嵌套遍历数组:

let result = [];
for (const subArr of nestedArray) {
    for (const item of subArr) {
        if (item.dropDownOne.key === testName.trim()) {
            result = item.dropDownTwo;
            // 找到后跳出循环提升效率
            break;
        }
    }
    if (result.length > 0) break;
}
console.log(result);

扩展:匹配多个结果

如果存在多个dropDownOne.key符合条件的对象,可以用filter+flatMap提取所有对应dropDownTwo数组:

const allResults = nestedArray.flat()
    .filter(item => item.dropDownOne.key === testName.trim())
    .flatMap(item => item.dropDownTwo);

内容的提问来源于stack exchange,提问作者Soumya Behera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:43:04