1

I have this function that returns an array of objects, I want data array to return like this "data": [5466, 25], pointsExchanged and pointsExpired return an array of objects like this: [ { 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]
      },
    ]
  };
}

Response from the function:

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

How i want the response to be:

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

            }
        ] }

1 Answer 1

1

simply map them and extract sum attribute and then merge them using spread operator ...

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.