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

如何转换API返回数据结构以适配Nivo折线图数据格式?

Transform Data for Nivo Line Chart

Got it, let's get your raw data formatted perfectly for Nivo's line chart. Here's a simple, clean approach using JavaScript to map your existing structure to the required format:

Step 1: Define your raw input data

First, let's start with the data you retrieved:

const rawInputData = { 
  data: [ 
    { ts: "20-10-26", events: 1500 }, 
    { ts: "20-10-27", events: 1280 }, 
    { ts: "20-10-28", events: 1111 } 
  ] 
};

Step 2: Transform the data

We'll use the map() method to rekey each object (swap ts to x, events to y), then wrap everything in the structure Nivo expects, including your static id and color fields:

const nivoLineChartData = [
  {
    id: "events",
    color: "hsl(331, 70%, 50%)",
    data: rawInputData.data.map(item => ({
      x: item.ts,
      y: item.events
    }))
  }
];

Result

Running this code will produce exactly the format you need:

[
  {
    "id": "events",
    "color": "hsl(331, 70%, 50%)",
    "data": [
      { "x": "20-10-26", "y": 1500 },
      { "x": "20-10-27", "y": 1280 },
      { "x": "20-10-28", "y": 1111 }
    ]
  }
]

This approach is scalable too—if you ever add more entries to your raw data, the map() method will automatically process them without any extra code. Just pass nivoLineChartData directly to your Nivo line chart component and you're good to go!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:03:15