如何在JavaScript嵌套对象或JSON中获取指定键值对的访问路径
嵌套对象唯一键值对访问路径获取方案
你可以通过递归深度优先遍历嵌套对象的方式生成访问路径,整体实现逻辑如下:
- 深度遍历对象/数组的每一层,遍历过程中记录当前层级的路径
- 匹配到目标key(或者key+唯一标识符的组合)时,返回拼接好的路径
- 未匹配到的分支做回溯处理,删除路径中当前层级的key
实现代码
import _ from 'lodash'; /** * 查找目标键值对对应的lodash可用访问路径 * @param {object} obj 待遍历的嵌套对象 * @param {string} targetKey 要查找的唯一key * @param {*} [targetValue] 可选,对应key的唯一标识符,传参会同时匹配key和值 * @returns {string|undefined} 点分隔格式的路径,未找到返回undefined */ function getLodashPath(obj, targetKey, targetValue) { const path = []; function traverse(current) { if (typeof current !== 'object' || current === null) return false; for (const key of Object.keys(current)) { path.push(key); // 匹配规则校验 if (key === targetKey && (targetValue === undefined || current[key] === targetValue)) { return path.join('.'); } // 递归遍历子节点 const res = traverse(current[key]); if (res) return res; // 回溯 path.pop(); } return false; } return traverse(obj) || undefined; }
使用示例
// 测试嵌套对象 const demoObj = { user: { info: { user_id: 'u_10086', name: '张三' } }, orderList: [ { order_id: 'o_20010', amount: 99 } ] }; // 查找匹配路径 const targetPath = getLodashPath(demoObj, 'user_id', 'u_10086'); console.log(targetPath); // 输出:user.info.user_id // 调用lodash.get取值 const targetValue = _.get(demoObj, targetPath); console.log(targetValue); // 输出:u_10086
补充说明:如果对象包含数组结构,生成的路径会自动带上数字下标(比如
orderList.0.order_id),lodash的_.get原生支持这种格式,无需额外转换。如果需要数组格式的路径,直接返回path数组即可,不需要调用join('.')。
内容的提问来源于stack exchange,提问作者employee
相关产品推荐
相关产品推荐

