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

如何用递归深度优先搜索获取JavaScript嵌套对象指定键的值

如何递归获取嵌套对象中指定键的值

我有一个嵌套的JavaScript对象,想要获取其中user键对应的值。之前用循环处理,但如果键嵌套在多层对象里,怎么写递归函数自动获取?

示例对象

{
  "http://converge.amwell.com/claims": {
    "ehr": "DEMO-CVSHI-EPIC-1",
    "connection": "con_9ydmEmrkyPulwlwU",
    "role": "PATIENT",
    "tenant": "CVSHI",
    "user": "b3e9c94d-18e4-4743-9f4e-fe7e251e7b17",
    "patient": "b3e9c94d-18e4-4743-9f4e-fe7e251e7b17",
    "id_type": "INTERNAL_FHIR"
  },
  "iss": "https://amwellstage.amwell-dev.auth0.com/",
  "sub": "oauth2|CVSHI-PATIENT|sick-cost@16xkn1tf.mailosaur.net",
  "aud": [
    "https://amwellstage.amwell-dev.auth0.com/api/v2/",
    "https://amwellstage.amwell-dev.auth0.com/userinfo"
  ],
  "iat": 1665480351,
  "exp": 1665481251,
  "azp": "cKftX4PfLpO0gFULuQiyDiX57BtTbpwg",
  "scope": "openid profile email offline_access",
  "org_id": "org_HMAePTi76uUGOfdG"
}

之前尝试的循环代码

for (const [key, value] of Object.entries(obj)) {
    // if (key === 'user') {
    //     user = value
    // }
    // if (value instanceof Object) {
    //     for (const [subKey, subValue] of Object.entries(value)) {
    //         if (subKey === 'user') {
    //             user = subValue
    //         }
    //     }
    // }
}

递归解决方案

基础版:找到第一个匹配的键值

这个函数会遍历对象的所有层级,找到第一个匹配的目标键就返回对应值,没找到则返回undefined。

function findNestedKey(obj, targetKey) {
  // 非对象/数组直接返回,避免报错
  if (obj == null || typeof obj !== 'object') {
    return undefined;
  }

  // 遍历当前对象的所有键
  for (const key of Object.keys(obj)) {
    const value = obj[key];
    // 找到目标键,直接返回值
    if (key === targetKey) {
      return value;
    }
    // 递归遍历子对象/数组,找到结果就返回
    const result = findNestedKey(value, targetKey);
    if (result !== undefined) {
      return result;
    }
  }

  // 遍历完所有层级没找到,返回undefined
  return undefined;
}

测试代码

把示例对象传入函数,就能拿到user的值:

const sampleObj = { /* 此处放入上述示例对象 */ };
const userId = findNestedKey(sampleObj, 'user');
console.log(userId); // 输出: b3e9c94d-18e4-4743-9f4e-fe7e251e7b17

扩展版:收集所有匹配的键值

如果你的对象里有多个层级都存在user键,可以用这个版本收集所有匹配的值,返回一个数组:

function findAllNestedKeys(obj, targetKey) {
  const results = [];
  if (obj == null || typeof obj !== 'object') {
    return results;
  }

  for (const key of Object.keys(obj)) {
    const value = obj[key];
    if (key === targetKey) {
      results.push(value);
    }
    // 递归收集子对象里的匹配值
    results.push(...findAllNestedKeys(value, targetKey));
  }

  return results;
}

内容的提问来源于stack exchange,提问作者jef chang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:20:27