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

TypeScript中不使用eval,如何通过对象路径字符串获取对象值?

解决JS/TS中通过路径字符串获取嵌套对象属性的问题

方案一:拆分路径后用reduce遍历

把路径字符串按.分割成键名数组,再通过reduce方法逐层访问对象属性,这是最直接的实现方式:

const obj = {
  a: {
    b: {
      c: 1
    }
  }
};
const path = "b.c";

// 路径"b.c"对应obj.a的子属性,所以从obj.a开始遍历
const targetValue = path.split('.').reduce((currentObj, key) => currentObj[key], obj.a);
console.log(targetValue); // 输出 1

方案二:封装健壮的通用工具函数

如果需要处理路径不存在的边界情况(避免抛出Cannot read property 'xxx' of undefined错误),可以封装一个更安全的工具函数:

function getNestedProperty(obj: unknown, path: string): unknown {
  return path.split('.').reduce((current, key) => {
    // 检查当前对象是否存在,避免访问undefined的属性
    if (current && typeof current === 'object' && key in current) {
      return (current as Record<string, unknown>)[key];
    }
    return undefined;
  }, obj);
}

// 使用示例
const targetValue = getNestedProperty(obj.a, "b.c");
console.log(targetValue); // 输出 1

注意事项

  • 给定的路径"b.c"是obj.a的子属性路径,因此遍历的起始对象是obj.a;如果路径是"a.b.c",则直接从obj开始遍历即可。
  • 避开eval是因为它存在代码注入风险,且TypeScript会明确禁止这类动态执行代码的写法,split+reduce的方式类型更安全,也符合TS的类型检查规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:16:05