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

如何获取嵌套对象与数组中目标值的最深层级对应键?

嵌套对象/数组中根据值查找最深层级键的方案

对于简单对象,我们可以轻松根据值获取对应键:

const simpleObject = {
    "a": "aaa",
    "b": "bbb",
};

// 根据值获取键的方法
Object.keys(simpleObject).find(key => simpleObject[key] === "aaa");

但面对包含数组和嵌套对象的复杂结构时,需要找到目标值对应的最深层级键路径:

const complexObject = {
    "A": [  "a1", {"a2": ["a21", "a22" ]}, "a3"],   // 紧凑写法
    "B": [                                          // 展开写法
            "b1", 
            "b2",
            {"b3": [
                    "b31", 
                    "b32"
                ]
            }
         ],
};

示例需求

输入输出
AA
a1A
a2A
a21A.a2

解决方案

1. 递归版本(支持无限层级嵌套)

通过递归遍历所有嵌套的对象和数组,记录当前路径,找到目标值时返回最深的路径:

function findDeepestKey(obj, target) {
    let result = null;
    let maxDepth = -1;

    function traverse(current, path = [], depth = 0) {
        // 当前值匹配目标,检查是否为更深层级路径
        if (current === target) {
            if (depth > maxDepth) {
                maxDepth = depth;
                result = path.join('.');
            }
            return;
        }

        // 遍历数组元素,路径不添加索引(需求中数组元素对应父级键)
        if (Array.isArray(current)) {
            current.forEach(item => traverse(item, [...path], depth));
            return;
        }

        // 遍历对象键值对
        if (typeof current === 'object' && current !== null) {
            Object.entries(current).forEach(([key, value]) => {
                // 检查键是否匹配目标
                if (key === target) {
                    if (depth + 1 > maxDepth) {
                        maxDepth = depth + 1;
                        result = [...path, key].join('.');
                    }
                }
                // 递归遍历值
                traverse(value, [...path, key], depth + 1);
            });
        }
    }

    traverse(obj);
    return result || null;
}

// 测试示例
console.log(findDeepestKey(complexObject, "A")); // "A"
console.log(findDeepestKey(complexObject, "a1")); // "A"
console.log(findDeepestKey(complexObject, "a2")); // "A"
console.log(findDeepestKey(complexObject, "a21")); // "A.a2"

2. 有限层级版本(支持2层级)

如果只需要支持到2层级嵌套,可简化逻辑避免递归:

function findKeyUpTo2Levels(obj, target) {
    // 检查顶层键是否匹配
    if (Object.keys(obj).includes(target)) {
        return target;
    }

    // 遍历顶层键值对
    for (const topKey of Object.keys(obj)) {
        const value = obj[topKey];
        
        // 处理顶层数组
        if (Array.isArray(value)) {
            for (const item of value) {
                if (item === target) return topKey;
                // 遍历数组中的嵌套对象
                if (typeof item === 'object' && item !== null) {
                    const subKeys = Object.keys(item);
                    if (subKeys.includes(target)) return topKey;
                    for (const subKey of subKeys) {
                        const subValue = item[subKey];
                        if ((Array.isArray(subValue) && subValue.includes(target)) || subValue === target) {
                            return `${topKey}.${subKey}`;
                        }
                    }
                }
            }
        }

        // 处理顶层对象
        if (typeof value === 'object' && value !== null) {
            const subKeys = Object.keys(value);
            if (subKeys.includes(target)) return topKey;
            for (const subKey of subKeys) {
                if (value[subKey] === target) return `${topKey}.${subKey}`;
            }
        }
    }

    return null;
}

// 测试示例
console.log(findKeyUpTo2Levels(complexObject, "a21")); // "A.a2"

说明

  • 递归版本会遍历所有嵌套层级,确保找到最深的键路径,完全匹配需求示例逻辑;
  • 有限层级版本逻辑更简洁,适合已知嵌套深度不超过2层的场景;
  • 所有代码均为纯JavaScript实现,可直接用于Fibery自动化脚本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:42:45