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

React组件中如何通过动态嵌套对象属性路径获取数据?

解决嵌套数据路径的动态取值问题

你遇到的问题是因为 row[column.field] 会把 column.field 的完整字符串(比如"attributes.name")当作对象的单一键名去查找,但你的数据是嵌套结构,实际需要的是先访问 row.attributes,再访问其下的 name 属性。

解决方案:实现嵌套路径取值函数

自己写一个轻量的工具函数,就能通过动态路径字符串获取嵌套数据里的值:

// 嵌套路径取值工具函数
const getNestedValue = (obj, path) => {
  // 将路径按点分割成数组,比如"attributes.name" → ["attributes", "name"]
  return path.split('.').reduce((currentValue, key) => {
    // 逐层访问对象属性,可选链?.避免路径不存在时报错
    return currentValue?.[key];
  }, obj);
};

在React表格渲染中使用

把这个函数用到你的表格渲染逻辑里,替换原来的row[column.field]:

<table>
  <thead>
    <tr>
      {columns.map(column => (
        <th key={column.field}>{column.header}</th>
      ))}
    </tr>
  </thead>
  <tbody>
    {props.data.data.map(row => (
      <tr key={row.id}>
        {columns.map(column => (
          <td key={column.field}>
            {getNestedValue(row, column.field)}
          </td>
        ))}
      </tr>
    ))}
  </tbody>
</table>

补充说明

  • 函数里的?.是可选链操作符,如果路径中的某一层不存在(比如某个row没有attributes字段),会返回undefined而不是抛出错误,避免页面崩溃。
  • 如果你的项目已经引入了Lodash库,也可以直接用_.get(row, column.field)实现同样的效果,无需自己编写函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:51:09