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

将Laravel后端数据转换为数组数组格式用于Vue前端图表展示

Convert Laravel Backend Data to Vue Chart Format

Got it, let's solve this data format conversion problem step by step.

First, let's look at your raw data from the Laravel backend:

const rawData = [ { "Jan": 120, "Feb": 283.5, "Mar": 10, "Apr": 233.92, "May": 327.78, "Jun": 190.74, "Jul": 10, "Aug": 10, "Sep": 10, "Oct": 10, "Nov": 10, "Dec": 10 } ];

This is an array containing a single object, where each key is a month and the value is the average order amount.

To convert this into the [["Jan", 120], ["Feb", 283.5], ...] format your chart needs, we can use JavaScript's built-in Object.entries() method—it's perfect for this scenario because it directly transforms an object's key-value pairs into the exact sub-arrays you want.

Here's the straightforward conversion code you can use in your Vue component:

// Extract the first (and only) object from the raw data array
const monthlyDataObject = rawData[0];

// Convert the object to the required 2D array format
const chartReadyData = Object.entries(monthlyDataObject);

Why this works:

  • Object.entries() iterates over all enumerable properties of the input object and returns an array of [key, value] pairs. Exactly matching your chart's expected structure.
  • Since your backend returns the months in chronological order (Jan to Dec), modern JavaScript engines preserve the insertion order of string keys in objects, so the resulting chartReadyData will maintain the correct month sequence for your chart.

If you need to handle edge cases (like if the backend ever returns multiple objects, or missing months), you can add a quick check:

// Handle cases where rawData might be empty or have multiple entries
const chartReadyData = rawData.length > 0 
  ? Object.entries(rawData[0])
  : []; // Fallback to empty array if no data

That's all! This conversion is efficient, clean, and leverages native JS methods so you don't need any extra libraries.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:09:14