I have and Array of Objects whose elements are randomly ordered. I would like to list the values in a specific order (of the keys).
As an example, the iteration below just lists them:
var vm = new Vue({
el: "#root",
data: {
all: [{
second: 2,
third: 3,
first: 1
},
{
third: 30,
first: 10,
second: 20
}
],
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="root">
<div v-for="a in all">
<div v-for="(v, k) in a">{{v}}</div>
</div>
</div>
Is this possible to drive the iteration so that it is ordered according to a list of keys (["first", "second", third"]
) which would yield
1
2
3
10
20
30
Yes. But hunting it down is a littlebit complicated, as for of doesn't only iterate arrays (like for in does enumerate objects). Instead, it generically iterates all iterable objects - in the order that their respective iterator supplies.
Iterating over an objectIf we loop over an object with a single argument, we'll be looping over all of the items. If we add another argument, we'll get the items AND keys. And if we add a third, we can also access the index of the v-for loop.
This can be accomplished by adding the v-for directive in the element that should be repeated. We can loop over the objects in the shoppingItems array and access the values using a given key. This will result in an unordered list with the values from the array.
I don't know vue but you can do it like this in javascript.
<div v-for="k in Object.keys(a).sort()">{{k}}:{{a[k]}}</div>
Also note that alphabetic sorting accidentally fits into your need, but you might need a custom sort function like sort((a,b)=>order.indexOf(a)-order.indexOf(b))
with your custom order order: ["first","second","third","fourth"]
which may not be alphabetic.
var vm = new Vue({
el: "#root",
data: {
all: [{
second: 2,
third: 3,
first: 1,
fourth: 4
},
{
third: 30,
first: 10,
second: 20,
fourth: 40
}
],
order: ["first","second","third","fourth"]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<div id="root">
<div v-for="a in all">
<div v-for="k in Object.keys(a).sort((a,b)=>order.indexOf(a)-order.indexOf(b))">{{k}}:{{a[k]}}</div>
<hr/>
</div>
</div>
You can put your list of sorted keys in an array and v-for
over that instead.
<div v-for="a in all">
<div v-for="key in presortedListOfKeys">
{{a[key]}}
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With