将Laravel后端数据转换为数组数组格式用于Vue前端图表展示
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
chartReadyDatawill 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

