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

如何在JavaScript中从Object的子属性查询对应的父级键名

问题原因

你现有代码的逻辑问题出在判断条件上:Object.values(e)拿到的是当前chapter下所有paragraph的值(也就是嵌套的对象),你拿这些对象和字符串类型的段落名section做匹配,自然永远返回false,所以找不到结果。

你需要匹配的是chapter对象的键名,而非值,修改判断逻辑即可:

// 把原来的这行
// const category = Object.entries(book).find(([, e]) => Object.values(e).includes(section));
// 修改为
const category = Object.entries(book).find(([, e]) => Object.keys(e).includes(section));

运行后就能拿到你期望的chapter2结果。


扩展:任意深度嵌套查找

如果你的对象嵌套层级不固定、需要跨多层找父键,可以用递归实现:

function findParentKey(obj, targetKey) {
  for (const [key, value] of Object.entries(obj)) {
    if (typeof value === 'object' && value !== null) {
      // 先判断当前层的键有没有匹配目标
      if (Object.keys(value).includes(targetKey)) {
        return key;
      }
      // 递归往下找
      const deepResult = findParentKey(value, targetKey);
      if (deepResult) return deepResult;
    }
  }
  return null;
}

// 调用示例
console.log(findParentKey(book, 'paragraph3')); // 输出chapter2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:24:05