首页 > 解决方案 > 如何正确格式化 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;
    }

标签: javascriptjquerylaravelmorris.js

解决方案


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 字符串,现在如果你解析它,你不应该得到任何错误


推荐阅读