如何通过键名匹配获取JSON文件的嵌套键对应值?现有方案无法生效
问题原因
你现有的实现存在两个核心问题:
- 只遍历了传入对象的第一层属性,没有处理嵌套层级的结构
- 逻辑写反了:你现在是把对象第一层的属性值和传入的嵌套路径字符串做匹配,永远不可能得到预期结果
解决方案
你需要先把点分隔的嵌套路径拆成键名数组,再逐层遍历对象取值即可,修正后的代码如下:
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
相关产品推荐
相关产品推荐

