Saya memiliki fungsi ini yang mengembalikan array objek, saya ingin array data kembali seperti ini "data": [5466, 25], pointsExchanged dan pointsExpired mengembalikan array objek seperti ini: [ { sum : '5466' } ]

export const getPieChart = async () => {
  const [pointsExchanged, pointsExpired] = await Promise.all([
    conn("statements")
      .sum("value")
      .where('type', 'deposito'),
    conn("statements")
      .sum("value")
      .where('type', 'exchange'),
  ]);

  return {
    labels: ['Pontos trocados', 'Pontos expirados', 'Pontos atribuidos'],
    datasets: [
      {
        backgroundColor: ["blue", 'red'],
        data: [pointsExchanged, pointsExpired]
      },
    ]
  };
}

Respon dari fungsi:

{
    "labels": [
        "Pontos trocados",
        "Pontos expirados",
        "Pontos atribuidos"
    ],
    "datasets": [
        {
            "backgroundColor": [
                "blue",
                "red"
            ],
            "data": [
                [
                    {
                        "sum": "5466"
                    }
                ],
                [
                    {
                        "sum": "25"
                    }
                ]
            ]
        }
    ] }

Bagaimana saya ingin tanggapannya:

{
        "labels": [
            "Pontos trocados",
            "Pontos expirados",
            "Pontos atribuidos"
        ],
        "datasets": [
            {
                "backgroundColor": [
                    "blue",
                    "red"
                ],
                "data": [5466, 25],

            }
        ] }
1
jarwin 8 Maret 2020, 01:15

1 menjawab

Jawaban Terbaik

Cukup petakan dan ekstrak atribut sum lalu gabungkan menggunakan operator spread ...

data: [
  ...pointsExchanged.map(point => Number(point.sum)), 
  ...pointsExpired.map(point => Number(point.sum))
]
const pointsExchanged = [{"sum": "5466"}];
const pointsExpired = [{"sum": "25"}];

const data = [
  ...pointsExchanged.map(point => Number(point.sum)), 
  ...pointsExpired.map(point => Number(point.sum))
];

console.log(data)
1
num8er 7 Maret 2020, 22:24