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

如何通过自定义函数动态获取对象的多层嵌套属性

最优实现方案

核心思路是将传入的点分隔属性路径拆分为属性队列,逐层遍历目标对象取值,同时内置边界容错避免属性不存在时抛出异常。

基础版(仅支持点分隔属性)

func(propertyName) {
  const propKeys = propertyName.split('.');
  let target = object;
  for (const key of propKeys) {
    // 中间层为空直接返回,避免抛Cannot read properties of undefined错误
    if (target == null) return undefined;
    target = target[key];
  }
  return target;
}

调用示例:如果object = {property1: {property2: '嵌套值'}},执行func('property1.property2')即可返回'嵌套值'。

增强版(兼容数组索引写法)

如果需要支持func('list[0].name')这类带数组下标的路径调用,可以对路径做预处理:

func(propertyName) {
  // 把[索引]替换为.索引,统一按点拆分,过滤空字符串避免路径开头/结尾的点导致异常
  const propKeys = propertyName.replace(/\[(\d+)\]/g, '.$1').split('.').filter(Boolean);
  let target = object;
  for (const key of propKeys) {
    if (target == null) return undefined;
    target = target[key];
  }
  return target;
}

可选优化:支持默认值

如果需要属性不存在时返回指定默认值而非undefined,可以增加参数配置:

func(propertyName, defaultValue = undefined) {
  const propKeys = propertyName.replace(/\[(\d+)\]/g, '.$1').split('.').filter(Boolean);
  let target = object;
  for (const key of propKeys) {
    if (target == null) return defaultValue;
    target = target[key];
  }
  return target ?? defaultValue;
}

调用示例:func('not.exist.prop', 'fallback值')会返回指定的fallback值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:57:03