I have an array - 'items'
of objects
and each of them contains an array
of more objects
.
I would like to access
the second array 'productPrices'
to use v-for
. But items.productPrices
doesn’t work for me. Should I create double loop somehow?
HTML:
<table> <tbody> <tr v-for="(element, index) in items.productPrices"> <td>{{ element.name }}</td> <td> <span>{{ element.amount }}</span> </td> <td> {{ element.price }} </td> </tr> </tbody> </table>
JS:
new Vue({ el: "#app", data: { items: [ { name: 'menu', path: 'menu', productPrices: [ { amount: 100, price: 80.61, name: 'first' }, { amount: 250, price: 72.10 }, { amount: 500, price: 79.62 }, { amount: 1000, price: 100.20 }, { amount: 2500, price: 147.60 }, { amount: 5000, price: 232.56 } ], quantity: 0 }, { name: 'Etui', path: 'etui', productPrices: [ { amount: 100, price: 80.61, name: 'first' }, { amount: 250, price: 72.10 }, { amount: 500, price: 79.62 }, { amount: 1000, price: 100.20 }, { amount: 2500, price: 147.60 }, { amount: 5000, price: 232.56 } ], quantity: 0 }, ] } })
Here is a fiddle.
Advertisement
Answer
While you can do this with <template> ... </template>
as the other two people have answered, if you wish to not nest another loop you can flatten all of the data into one array to be used, it won’t be as pretty unless you move it to a function or the like.
Here’s how:
<div id="app"> <table> <tbody> <!-- <tr v-for="(element, index) in items.map(item => item.productPrices).reduce((joinedArrays, currentArray) => joinedArrays.concat(currentArray), [])"> --> <tr v-for='(element, index) in currentItem().productPrices'> <td>{{ element.name }}</td> <td> <span>{{ element.amount }}</span> </td> <td> {{ element.price }} </td> </tr> </tbody> </table>