0

How can I render data with loop

(for; v-for) inside: { labels: [] } and datasets: [{ data:[] }]

in chart using (Vue-Chart.js)

data: {
                    labels: [

                        ***HERE***

                    ],
                    datasets: [{
                        label: "Assets",
                        backgroundColor: ["#4285F6"],
                        data: [

                            ***HERE***

                        ],                 
                    }],
                },

So far, my (render) data is (an array, inside it - few objects - and inside every objects all my data needs):

LABELS: 
this.array[0] ? this.array[0].asset.name : '',
this.array[0] ? this.array[1].asset.name : '',
this.array[0] ? this.array[2].asset.name : '',

DATASETS:
this.array[0] ? this.array[0].amount : '',
this.array[0] ? this.array[1].amount : '',
this.array[0] ? this.array[2].amount : '',  
6
  • What does your data looks like? Commented Oct 10, 2018 at 8:23
  • Pal, I've edit my comment and add it there. Commented Oct 10, 2018 at 8:29
  • Why don't you create a new array, put data inside it with a loop and then use it in vue chart config? Commented Oct 10, 2018 at 8:47
  • in your loop, you check for this.array[0] condition everytime? Commented Oct 10, 2018 at 8:49
  • I don't have access to the data(API), so I have to use it in that way :\ Yes, because if not - it returns me undefined. Commented Oct 10, 2018 at 8:53

1 Answer 1

2

Before your chart config, create a new array and then use it:

var labelsArray = [];
var amountArray = [];
for (var i = 0; i < this.array.length; i++) {
    labelsArray.push(this.array[i] ? this.array[i].asset.name : '');
    amountArray.push(this.array[i] ? this.array[i].amount : '');
}

Vue chart config will go like:

data: {
    labels: labelsArray ,
    datasets: [{
        label: "Assets",
        backgroundColor: ["#4285F6"],
        data: amountArray,                 
    }],
},
Sign up to request clarification or add additional context in comments.

1 Comment

This one helped me out a lot as well!

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.