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

如何提取JavaScript对象层级键并按分支分组为二维数组?

提取嵌套JavaScript对象的层级键数组

给定如下嵌套结构的JavaScript对象:

const obj = {
  "test1": {
    "test12": "val1",
    "test13": {
      "test131": "val1",
      "test132": "val2"
    }
  },
  "test2": "val2"
}

需要提取出所有键,按顶层键分组,将每个顶层键及其所有嵌套子键整理为一维数组,最终得到如下格式的二维数组:

const keys = [["test1", "test12", "test13", "test131", "test132"], ["test2"]];

实现方案

可以通过递归遍历的方式完成需求,具体代码如下:

function extractNestedKeys(obj) {
  const result = [];
  // 遍历每个顶层键
  for (const topKey of Object.keys(obj)) {
    const keyList = [topKey];
    // 递归收集所有子键
    function collectSubKeys(currentValue) {
      if (typeof currentValue === 'object' && currentValue !== null) {
        const subKeys = Object.keys(currentValue);
        keyList.push(...subKeys);
        subKeys.forEach(key => collectSubKeys(currentValue[key]));
      }
    }
    collectSubKeys(obj[topKey]);
    result.push(keyList);
  }
  return result;
}

// 测试使用
const obj = {
  "test1": {
    "test12": "val1",
    "test13": {
      "test131": "val1",
      "test132": "val2"
    }
  },
  "test2": "val2"
};

const keys = extractNestedKeys(obj);
console.log(keys); // 输出目标格式的数组

逻辑说明

  1. 遍历对象的每个顶层键,为每个顶层键初始化一个包含自身的键数组
  2. 递归处理顶层键对应的值:若当前值是对象(且不为null),则提取该对象的所有子键加入数组,再继续遍历每个子键对应的值,重复收集操作
  3. 每个顶层键对应的键数组处理完成后,加入最终结果数组

额外说明

如果对象中存在不同层级的同名键,数组会包含重复项。若需要去重,可以将keyList的最终值替换为[...new Set(keyList)]。

内容的提问来源于stack exchange,提问作者Masoud Tesna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:30:58