前端数据的处理

82 阅读1分钟

一、Echarts中月份的处理

  • 我们在写echarts的时候,后端返回的数据往往不是我们要需要的数据结构

  • 后端返回的数据

    let list = [
      { monthDesc: "2024-08", totalNum: 1 },
      { monthDesc: "2024-09", totalNum: 10 },
      { monthDesc: "2024-10", totalNum: 2 }
    ];
    
  • 渲染需要的数据 image.png

  • 数据的处理

    let list = [
      { monthDesc: "2024-08", totalNum: 1 },
      { monthDesc: "2024-09", totalNum: 10 },
      { monthDesc: "2024-10", totalNum: 2 }
    ];
    
    // 生成一个包含目标年份所有月份的数组
    const allMonths = Array.from({ length: 12 }, (_, i) => {
      let date = new Date();
      let year = date.getFullYear();
      return `${year}-${(i + 1).toString().padStart(2, "0")}`;
    });
    
    // 初始化总数数组,所有月份都初始化为0
    let totalNumArray = allMonths.map(() => 0);
    
    // 遍历list,将totalNum放入对应的月份位置
    list.forEach(item => {
      const index = allMonths.indexOf(item.monthDesc);
      if (index !== -1) {
        totalNumArray[index] = item.totalNum;
      }
    });
    console.log("月份数组:", allMonths);
    console.log("总数数组:", totalNumArray);
    
  • 处理的结果 image.png