如何转换API返回数据结构以适配Nivo折线图数据格式?
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

