You need to enable JavaScript to run this app. 如何通过键名匹配获取JSON文件的嵌套键对应值?现有方案无法生效
优惠活动
大模型
产品
解决方案
定价
更多

如何通过键名匹配获取JSON文件的嵌套键对应值?现有方案无法生效

问题原因

你现有的实现存在两个核心问题:

  1. 只遍历了传入对象的第一层属性,没有处理嵌套层级的结构
  2. 逻辑写反了:你现在是把对象第一层的属性值和传入的嵌套路径字符串做匹配,永远不可能得到预期结果

解决方案

你需要先把点分隔的嵌套路径拆成键名数组,再逐层遍历对象取值即可,修正后的代码如下:

const paths = require(`../locales/en-US.json`)

const getValueByKeyPath = (obj, keyPath) => {
  // 将点分割的路径拆为键名数组
  const keyList = keyPath.split('.')
  let currentValue = obj
  for (const key of keyList) {
    // 遇到不存在的键直接返回,避免报错
    if (currentValue === null || currentValue === undefined || !Object.hasOwn(currentValue, key)) {
      return undefined
    }
    currentValue = currentValue[key]
  }
  return currentValue
}

// 调用后即可得到预期的 login 结果
console.log(getValueByKeyPath(paths, 'routes.path.login.index'))

进阶优化

如果需要支持带数组下标的路径格式(比如routes.path.userList[0].index),可以调整路径拆分的逻辑,适配方括号写法:

const getValueByKeyPath = (obj, keyPath) => {
  // 把方括号写法转换为点分割格式,再拆成键名数组
  const keyList = keyPath.replace(/\[(\d+)\]/g, '.$1').split('.').filter(Boolean)
  let currentValue = obj
  for (const key of keyList) {
    if (currentValue === null || currentValue === undefined || !Object.hasOwn(currentValue, key)) {
      return undefined
    }
    currentValue = currentValue[key]
  }
  return currentValue
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 15:24:04