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

如何替代JavaScript的eval来动态读取嵌套JSON对象属性?

替代eval读取JSON嵌套属性的方案

问题描述

我需要通过动态函数读取JSON对象中的属性值,示例JSON对象如下:

var test = 
{
  "test1": {
    "test2": "value2"
  },
  "test3": {
    "test4": {
      "test5": "value5"
    }
  }
}

目前我通过传入属性路径字符串(如'test1.test2'、'test3.test4.test5'),使用以下基于eval的代码实现了读取功能,代码可正常运行,但想了解是否存在替代eval的方案:

readValue('test1.test2');
readValue('test3.test4.test5');

function readValue(val){
  console.log(eval(`test.${val}`));
}

可行替代方案

方案1:split + reduce 逐层遍历

这是最轻量化的原生实现方式,无需依赖任何工具库。将路径字符串按.分割为属性名数组,再用reduce方法逐层遍历目标对象:

function readValue(path) {
  return path.split('.').reduce((currentObj, key) => {
    // 处理属性不存在的情况,避免抛出TypeError
    return currentObj ? currentObj[key] : undefined;
  }, test);
}

// 调用示例
console.log(readValue('test1.test2')); // 输出: value2
console.log(readValue('test3.test4.test5')); // 输出: value5
console.log(readValue('test1.nonexistentKey')); // 输出: undefined

方案2:递归遍历路径

如果需要处理更复杂的路径场景(比如后续要支持数组索引),可以用递归方式实现:

function readValue(targetObj, pathSegments) {
  // 路径遍历完成,返回当前对象
  if (pathSegments.length === 0) return targetObj;
  const currentKey = pathSegments.shift();
  // 若当前属性存在则继续递归,否则返回undefined
  return targetObj?.[currentKey] ? readValue(targetObj[currentKey], pathSegments) : undefined;
}

// 调用时先拆分路径字符串
console.log(readValue(test, 'test1.test2'.split('.')));
console.log(readValue(test, 'test3.test4.test5'.split('.')));

方案3:使用工具库(如Lodash)

如果项目中已经引入Lodash工具库,直接使用_.get方法即可,它内置了嵌套属性的安全读取逻辑,还支持设置默认值:

// 确保已引入Lodash
// const _ = require('lodash'); // Node.js环境
// import _ from 'lodash'; // ESModule环境

console.log(_.get(test, 'test1.test2')); // 输出: value2
console.log(_.get(test, 'test3.test4.test5')); // 输出: value5
// 属性不存在时返回指定默认值
console.log(_.get(test, 'test1.invalidKey', 'defaultValue')); // 输出: defaultValue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:20:31