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

ReactJS嵌套循环JSON对象遇问题,求可行解决方案

在ReactJS中处理嵌套JSON数组的循环方案

嗨,这事儿不难!在React里处理这种嵌套的JSON数组,咱们用map()方法就能轻松搞定,这也是React里遍历列表最常用的方式。我给你写个完整的示例,你一看就懂:

完整组件示例

import React from 'react';

// 你的嵌套JSON数据
const alertData = [
  { 
    "id":1, 
    "time":"2018-04-15 22:04:21", 
    "alert":{ "id":6, "name":"Alert Test 416" }, 
    "source":{ "type":"Service", "id":37379, "name":"489-127-2367" }, 
    "value":1310384.000000 
  }, 
  { 
    "id":1, 
    "time":"2018-04-15 22:04:21", 
    "alert":{ "id":6, "name":"Alert Test 416" }, 
    "source":{ "type":"Service", "id":37826, "name":"489-332-4137" }, 
    "value":1352071.000000 
  },
  // 剩下的条目可以继续添加在这里
];

const AlertList = () => {
  return (
    <div className="alert-list">
      <h2>Alert Records</h2>
      {/* 遍历alertData数组 */}
      {alertData.map((item) => (
        // 注意:key要唯一,这里用item.id + item.source.id组合,避免重复
        <div key={`${item.id}-${item.source.id}`} className="alert-item">
          <p><strong>ID:</strong> {item.id}</p>
          <p><strong>Time:</strong> {item.time}</p>
          <p><strong>Alert:</strong> {item.alert.name} (ID: {item.alert.id})</p>
          <p><strong>Source:</strong> {item.source.name} (Type: {item.source.type}, ID: {item.source.id})</p>
          <p><strong>Value:</strong> {item.value.toFixed(2)}</p>
          <hr />
        </div>
      ))}
    </div>
  );
};

export default AlertList;

关键知识点说明

  • 数组遍历:使用Array.map()方法遍历JSON数组,每个数组元素对应生成一个React元素节点,这是React处理列表的标准方式。
  • 唯一Key属性:React要求列表中的每个元素必须拥有唯一的key,用来帮助React识别元素的变化。由于你的数据中存在id重复的情况(比如前两个条目id都是1),所以我用${item.id}-${item.source.id}组合成唯一标识,避免key冲突。
  • 嵌套对象访问:直接通过点语法item.alert.name、item.source.type访问嵌套属性即可。如果担心数据中可能存在属性缺失的情况,可以使用可选链操作符?.来避免报错,比如:
    <p><strong>Alert:</strong> {item.alert?.name || 'N/A'} (ID: {item.alert?.id || 'N/A'})</p>
    
    这样当alert属性不存在时,会显示N/A而不是崩溃。
  • 数值格式化:用toFixed(2)将value字段格式化为两位小数,提升显示的可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:33:23