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

如何在React.js中正确展示JSON记录的所有子属性值

解决React中访问嵌套JSON字段的问题

嘿,我看你已经成功渲染出context和id字段啦!剩下的字段因为嵌套在多层对象和数组里,咱们只需要顺着数据结构一步步访问就能拿到它们~

先理清楚你的数据结构

每个results项里的service是一个数组,里面的对象又包含attributes,而你要的字段分散在attributes.main和attributes.additionalInformation里:

  • productname、price → obj.service[0].attributes.main
  • categories、tags、description → obj.service[0].attributes.additionalInformation

修改后的代码示例

把你的render方法里的列表项改成下面这样,就能显示所有需要的字段了:

render() {
  return (
    <div>
      <ul>
        {this.state.rec.results.map((obj, i) => {
          // 先把嵌套的字段提取出来,让代码更清晰
          const serviceAttr = obj.service[0].attributes;
          const mainInfo = serviceAttr.main;
          const additionalInfo = serviceAttr.additionalInformation;
          
          return (
            <li key={i} style={{ marginBottom: '15px' }}>
              <p><strong>ID:</strong> {obj.id}</p>
              <p><strong>Context:</strong> {obj.context}</p>
              <p><strong>Product Name:</strong> {mainInfo.productname}</p>
              <p><strong>Price:</strong> {mainInfo.price}</p>
              <p><strong>Categories:</strong> {additionalInfo.categories.join(', ')}</p>
              <p><strong>Tags:</strong> {additionalInfo.tags.join(', ')}</p>
              <p><strong>Description:</strong> {additionalInfo.description}</p>
            </li>
          )
        })}
      </ul>
    </div>
  );
}

几个小细节说明

  1. 为什么用service[0]?
    因为你的service是数组类型,每个results项里只有一个service对象,所以用索引0直接取第一个元素。如果以后service可能有多个项,你可以再嵌套一个map来遍历它。

  2. 数组转字符串
    categories和tags是数组,用join(', ')可以把数组元素转成逗号分隔的字符串,显示更友好。

  3. 提取变量优化代码
    把嵌套的字段提前提取成变量,避免重复写长长的访问路径,代码可读性会更高~

这样修改后,你就能看到所有需要的字段内容啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 07:42:42