简体   繁体   中英

Making object of items in decending order data object in vue.js

In vue.js, in my data object I have an object of items that are sorted in one order. I want to make it in decending order. My vue template looks like below snippet -

<div class="form-element form-element-checkbox" :key="key" v-for="(value, key) in items">
          <input
            :id="getID(value)"
            type="checkbox"
            :value="value"
            @change="updateFilter"
            v-model="selections"
            :checked="isSelected(value)">
          <label class="chk-small" :for="getID(value)">
            <span :aria-label="`Rated ${key}.0 out of 5`" class="star-rating noBlank" :style="{ width: `${key * 20}px` }"></span>
          </label>
        </div>

And items object looks like

data() {
      return {
        items: {
          5: 'item_5',
          4: 'item_4',
          3: 'item_3'
        },
        selections: []
      };
    },

Storing data in that order does't work.Tried to use items.slice().reverse() also. What might be wrong here ? I'm not able to get.

If you cannot / do not want to change your items dictionary into an array, you can simply use Object.keys() to extract its keys and work on them.

 new Vue({ el: '#app', data() { return { items: { // Note: even though you write them in descending order, // the JS engine will list them in ascending order. 5: 'item_5', 4: 'item_4', 3: 'item_3', }, }; }, }); 
 <script src="https://unpkg.com/vue@2"></script> <div id="app"> <p>itemsKeys: {{Object.keys(items)}}</p> <ol> <li v-for="(key, keyIndex) of Object.keys(items).reverse()"> keyIndex: {{keyIndex}} / item key: {{key}} / item value: {{items[key]}} </li> </ol> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM