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

Node.js:如何通过预定义属性路径获取对象深层属性?

通过属性路径获取嵌套对象中的数据

问题场景

比如你有这样一个嵌套对象:

const obj = { 
  xy: { 
    item: [ 
      { z: { type: '1', id: 'myId', label: 'd', unit: 'dd', value: '11.20' } }
    ] 
  } 
};

还有一条属性路径字符串:

const path = "xy.item[0].z.value";

直接用obj[path]无法拿到目标值,因为这种写法仅支持单个属性名,解析不了链式的嵌套路径。

几种简单可行的解决方案

1. 手动解析路径遍历取值

把路径字符串拆分成单个属性节点,依次遍历访问对象:

function getNestedValue(obj, path) {
  // 将`item[0]`格式转换为`.item.0`,统一分割规则
  const nodes = path.replace(/\[(\d+)\]/g, '.$1').split('.');
  let current = obj;
  for (const node of nodes) {
    if (current == null) return undefined; // 路径不存在时返回undefined
    current = current[node];
  }
  return current;
}

// 使用示例
console.log(getNestedValue(obj, path)); // 输出 '11.20'

2. 用reduce简化实现

借助数组的reduce方法,结合可选链操作符精简代码:

const getNestedValue = (obj, path) => 
  path.replace(/\[(\d+)\]/g, '.$1')
      .split('.')
      .reduce((current, node) => current?.[node], obj);

// 使用示例
console.log(getNestedValue(obj, path)); // 输出 '11.20'

这里的?.是可选链操作符,当路径中某个节点不存在时,会直接返回undefined,避免抛出错误。

3. 注意事项

  • 如果属性名包含.、[这类特殊字符,上述方法需要调整分割规则,否则会解析出错。
  • 若频繁需要这类操作,也可以使用成熟工具库(比如lodash的_.get方法),但简单场景下手动实现更轻量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:17:06