如何在JavaScript中通过变量作为键获取嵌套对象的值?
动态访问嵌套JSON属性的几种方法
你遇到的这个问题太常见了——当属性路径是字符串形式时,直接用.访问肯定行不通,因为jsonObj.jsonKey会把jsonKey当成一个字面量属性名,而不是变量里存的那个路径字符串。下面给你几个实用的解决办法:
方法1:手动拆分路径 + 循环遍历
这是最直观的思路:把路径按.拆成单个属性名的数组,然后逐层遍历对象拿到最终属性,还能顺便处理路径不存在的异常情况:
var jsonObj = { "response":{ "result":{ "status":{ "name": "Eric" } } } } var jsonKey = "response.result.status.name"; // 把路径拆成属性名数组 var keys = jsonKey.split('.'); var currentValue = jsonObj; // 逐层访问嵌套属性 for (let key of keys) { if (currentValue && currentValue.hasOwnProperty(key)) { currentValue = currentValue[key]; } else { // 路径不存在时的兜底处理,比如返回undefined或默认值 currentValue = undefined; break; } } console.log("the status is: " + currentValue); // 输出 "the status is: Eric"
方法2:用Array.reduce简化代码
ES6的reduce方法能让这个过程更简洁,几行代码就能封装成可复用的工具函数:
var jsonObj = { "response":{ "result":{ "status":{ "name": "Eric" } } } } var jsonKey = "response.result.status.name"; // 封装成通用函数 const getNestedValue = (obj, path) => { return path.split('.').reduce((current, key) => { // 每一层都做存在性判断,避免报错 return current && current[key] ? current[key] : undefined; }, obj); }; console.log("the status is: " + getNestedValue(jsonObj, jsonKey)); // 输出 "the status is: Eric"
方法3:ES2020可选链(简洁但注意环境兼容)
如果你的运行环境支持ES2020及以上,可以用可选链操作符?.进一步简化代码,它会自动处理属性不存在的情况,不会抛出错误:
var jsonObj = { "response":{ "result":{ "status":{ "name": "Eric" } } } } var jsonKey = "response.result.status.name"; const getNestedValue = (obj, path) => { return path.split('.').reduce((current, key) => current?.[key], obj); }; console.log("the status is: " + getNestedValue(jsonObj, jsonKey)); // 输出 "the status is: Eric"
⚠️ 额外提醒:别用eval来实现!虽然eval(jsonObj.${jsonKey})能直接拿到结果,但它存在严重的安全风险——如果路径字符串被注入恶意代码,会直接执行,绝对不推荐在生产环境使用。
内容的提问来源于stack exchange,提问作者tiger_groove
相关产品推荐
相关产品推荐

