0

I get all the values of expirationdate and price in the loop. How do I write them to a variable and how do I specify them in labels: [],data: []?

success: function (data) {
            if (data.result) {
                for (let i = 0; i < data.result.length; i++) {
                    console.log(data.result[i].expirationdate);
                    console.log(data.result[i].price);

                }
                var ctx = document.getElementById("myChart").getContext("2d");
                    var chart = new Chart(ctx, {
                        type: 'line',
                        data: {
                             labels: [],
                            datasets: [{
                                label: 'Payment',
                                backgroundColor: 'rgb(255, 99, 132)',
                                borderColor: 'rgb(255, 99, 132)',
                                data: [],
                            }]
                        },
                        options: {}
                    });
            }
        }
2
  • Do you want the expirationdate to fill the labels property, and price to fill the data property? If not, please edit your question to better explain. Commented May 7, 2021 at 10:25
  • 1
    I want to insert data.result[i].expirationdate in labels: [] and data.result[i]. price in data: [] Commented May 7, 2021 at 10:27

1 Answer 1

1

This should work:

    success: function (data) {
                if (data.result) {
                    var expirationdates = [];
                    var prices = [];
                    for (let i = 0; i < data.result.length; i++) {
                        labels.push(data.result[i].expirationdate);
                        prices.push(data.result[i].price);
                    }
                    
                    var ctx = document.getElementById("myChart").getContext("2d");
                    var chart = new Chart(ctx, {
                        type: 'line',
                        data: {
                             labels: expirationdates,
                            datasets: [{
                                label: 'Payment',
                                backgroundColor: 'rgb(255, 99, 132)',
                                borderColor: 'rgb(255, 99, 132)',
                                data: prices,
                            }]
                        },
                        options: {}
                    });
                }
            }

However, I can't test it without an example of the data object.

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

1 Comment

Edited to make the assignment much clearer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.