I am trying to render the data in the desc
order, but vue 3 always render it in the asc
order
state: {
entries: {
2022: {
10: {...},
11: {...},
12: {...},
...
},
2021: {
10: {...},
12: {...},
...
},
2020: {
3: {...},
8: {...},
...
},
},
}
But it always renders like this 2020, 2021, 2022
where as I require it to be 2022, 2021, 2020
,
How to fix it
CodePudding user response:
JavaScript objects are in fact ordered, and the order of their keys/properties can be changed. Here’s how you can sort an object by its keys/properties:
var unordered = { b: 'b', c: 'c', a:'a'}
var ordered = Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
console.log(ordered) //{a: 'a', b: 'b', c: 'c'}
EDIT: I saw that you wanted it to be descending, you can use .sort.reverse for that purpose.
CodePudding user response:
integers are iterated first in the ascending order
Small Demo demonstrating above statement.
var jsonObj = {
3: 'March',
1: 'Jan',
5: 'May'
};
console.log(jsonObj);
That's what a JavaScript engine recognizes as an integer and what humans recognize as a number are not same.
To achieve the order, we can convert that object into an array.
Demo :
const app = new Vue({
el: '#app',
data() {
return {
list: [{
3: 'March' }, {
1: 'Jan' }, {
5: 'May' }]
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>
<body>
<div id="app">
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item[Object.keys(item)[0]] }}
</li>
</ul>
</div>
</body>