Alex T
Alex T

Reputation: 3764

Create data array with loop in vue

I have this data array holding repetitive item in the component:

data () {
datasets: [ {
        text: "",
        value:[ {
          x: "",
          y: "",
          type: 'bar'
        }]
        },
          {
        text: "",
        value: [{
          x: "",
          y: "",
          type: 'bar'
        }]
        },
        {
        text: "",
        value: [{
          x: "",
          y: "",
          type: 'bar'
        }]
        }
]
}

As you can see those are the same items. Is it possible to set this data like

datasets:[ {
        text: "",
        value:[ {
          x: "",
          y: "",
          type: 'bar'
        }]
        } * 3 ]

Instead of hardcoding it several times?

Upvotes: 1

Views: 171

Answers (1)

Estus Flask
Estus Flask

Reputation: 223259

It is:

datasets: Array(3).fill().map(() => ({
  text: "",
  value:[ {
    x: "",
    y: "",
    type: 'bar'
  }]
}))

In case elements are guaranteed to be read-only and can benefit from holding a reference to the same object, it can be:

datasets: Array(3).fill({
  text: "",
  value:[ {
    x: "",
    y: "",
    type: 'bar'
  }]
})

Upvotes: 3

Related Questions