Mr.Singh
Mr.Singh

Reputation: 1781

Vue 3: Rendering the object in descending order issue

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,

enter image description here

How to fix it

Upvotes: 0

Views: 437

Answers (1)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27202

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>

Upvotes: 1

Related Questions