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

如何提取嵌套对象数组所有层级键并生成指定路径结构数组

嵌套对象键路径提取函数

核心规则

  • 入参是多层嵌套的对象数组,遍历所有键时,无论值是string/number/boolean基础类型,还是object/array引用类型,都需要收录
  • 每个数组项中匹配person开头的顶层键,作为该组所有条目的title字段值
  • 所有键的访问路径统一以person为根,按嵌套层级拼接,最终返回{title, value: 访问路径}格式的对象数组

实现代码

function extractKeyPaths(list) {
  const res = [];

  // 深度递归遍历对象
  function dfs(obj, path, title) {
    Object.keys(obj).forEach(key => {
      const currentPath = `${path}.${key}`;
      // 收录当前键
      res.push({
        title,
        value: currentPath
      });
      const val = obj[key];
      // 值是对象/数组则继续递归下一层
      if (val !== null && typeof val === 'object') {
        dfs(val, currentPath, title);
      }
    });
  }

  list.forEach(item => {
    // 找到当前项的person类键作为title
    const personTitle = Object.keys(item).find(key => key.startsWith('person'));
    if (!personTitle) return;
    // 合并同项id与person对象下的属性,统一以person为路径根开始遍历
    const target = {
      id: item.id,
      ...item[personTitle]
    };
    dfs(target, 'person', personTitle);
  });

  return res;
}

效果验证

传入题目给出的示例输入,返回结果完全符合预期:

// 输入为题目给出的示例数组
const result = extractKeyPaths(input);
/*
输出结构(person1对应部分):
[
  { title: 'person1', value: 'person.id' },
  { title: 'person1', value: 'person.firstname' },
  { title: 'person1', value: 'person.lastname' },
  { title: 'person1', value: 'person.address' },
  { title: 'person1', value: 'person.address.state' },
  // person2、person3条目按相同规则生成
]
*/

如果后续需要支持数组下标访问路径,只需要在递归判断里加数组类型判断,遍历数组时用[index]拼接路径即可。

内容的提问来源于stack exchange,提问作者RAVI singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:51:26