Osman Rafi
Osman Rafi

Reputation: 1046

How can I fill an array by calling a method in Vue js?

I am trying to fill an array, declared in data property, by calling a function in methods property in Vue js. Here is the code:

<script>
export default {
  extends: Bar,
  mounted() {
    this.renderChart(this.chartData, this.options);
    this.fillLabel();
  },
  data() {
    return {
      chartData: {
        labels:[],
        datasets: [
          {
            label: "Users",
            data: [40,20,12,39,10,40]
          }
        ]
      },

    };
  },
  methods: {
    fillLabel() {
      this.chartData.datasets[0].data.map(function (key,value) {
          this.chartData.labels.push(key);
      })

    }
  }
};
</script>

But this gives me following error in console :

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'chartData' of undefined"

So how can I fill the labels array(inside chatData) by 0 to length of data array(inside datasets).

I am looking for your help. Thanks in advance.

Upvotes: 1

Views: 1485

Answers (2)

Saeed Jamali
Saeed Jamali

Reputation: 1195

Only need to introduce this to your fillLabel method as below: I tried this solution nd it fixed the problem

fillLabel() {
            let th = this;
            th.chartData.datasets[0].data.map(function (key,value) {
                th.chartData.labels.push(key);
            })
            alert(th.chartData.labels)

        },

Upvotes: 1

Prabhat Gupta
Prabhat Gupta

Reputation: 137

This is due to the fact that your function inside your map function will loose the this context. and so its getting undefined.

to solve this problem use an arrow function inside your map.

this.chartData.datasets[0].data.map((key,value)=> { this.chartData.labels.push(key); })

this will solve the problem

Upvotes: 1

Related Questions