javascript - 如何正确格式化 morris js 的数据
问题描述
我正在使用 morris js 在我的应用程序中创建图表。我有来自后端的回复,如下所示
{ duration: '', income: 0, expense:0 },
bur 因为 morris js 需要数组,所以我尝试在下面的数组中分配
results = [response.income_expense];
在我控制台记录这个值时分配后,我得到低于输出
console.log(results);
["{ duration: '', income: 0, expense:0 },"]
0: "{ duration: '', income: 0, expense:0 },"
但我想要一个如下所示的输出
(4) [{…}, {…}, {…}, {…}]
0: {duration: "2021", income: 537000, expense: 337000}
1: {duration: "2020", income: 368500, expense: 568500}
2: {duration: "2019", income: 268500, expense: 168500}
3: {duration: "2018", income: 368500, expense: 568500}
请帮助我获得所需的输出
另外我在后端有这个功能
public function dashboardData(Request $request)
{
try {
$data = $this->widgets($request->type);
$data['income_expense'] = $this->incomeExpense($request->type);
return $data;
} catch (\Exception $e) {
LogActivity::errorLog($e->getMessage());
return response()->json([
'error' => trans('common.Something Went Wrong')
]);
}
}
这是我的特点
public function incomeExpense($type): string
{
$chart_data_yearly = '';
$income_expense = $this->transactionRepo->incomeExpense($type);
// dd($income_expense);
foreach ($income_expense as $k => $row) {
$income = $this->transactionRepo->incomeByDate($row->transaction_date, $type);
$expense = $this->transactionRepo->expenseByDate($row->transaction_date, $type);
$chart_data_yearly .= "{ duration: '" . $row->duration . "', income: " . $income . ", expense:" . $expense . " },";
}
return $chart_data_yearly;
}
解决方案
public function incomeExpense($type): string
{
$chart_data_yearly = '';
$income_expense = $this->transactionRepo->incomeExpense($type);
// dd($income_expense);
foreach ($income_expense as $k => $row) {
$income = $this->transactionRepo->incomeByDate($row->transaction_date, $type);
$expense = $this->transactionRepo->expenseByDate($row->transaction_date, $type);
@$return[] = ['duration' => $row->duration,'income'=>$income,'expense' =>$expense]
}
return json_encode($chart_data_yearly);
}
这就是我会做的,将所有行推入一个数组,然后返回一个 jsonencoded 字符串,现在如果你解析它,你不应该得到任何错误
推荐阅读
- wordpress - 限制管理员在 wordpress 多站点中添加用户
- python - 计算股票交易中的信号
- visual-studio-code - 用于导入 Angular 材质模块的 VSCode 片段
- node.js - 节点 CORS 在 Chrome 上很好,但在 Safari / Firefox 上不行
- powerbi - Power BI 在矩阵报表中将一行的值与另一行的值相除
- c - 将C中的结构初始化为空还是零?
- python - 我如何用数字 1 随机填充半个数组
- sas - 如何根据 SAS 中的值创建新列
- python - 我正在使用遗传算法来解决迷宫,但它似乎不起作用,并且想知道是否有人可以指出我所做的错误(python)
- rust - 为什么 Rust 要求“一个值一旦固定,就必须永远固定”?