1

When I try using a hard-coded example, the real behaviour of select options are like this:

<select>
   <option value="3">C</option>
   <option value="1">A</option>
   <option value="2">B</option>
</select>

order is : C, A, B

However, when I try Vue, it orders them as keys:

data: {
    obj: {
      "2": "BBB",
      "1": "AAA",
      "3": "CCC"
    }
 }

<select>
   <option v-for="(item, key) in obj" :value="key">{{ item }}</option>
</select>

order is : AAA, BBB, CCC 

So it ordered them as key values.

In this scenario, is there a way to order them as the object's order rather than keys?

Like: BBB, AAAA, CCC

Here is a fiddle where I tested both cases:

https://jsfiddle.net/1Ljd96qk/

senty
  • 12,385
  • 28
  • 130
  • 260

1 Answers1

1

Properties order in javascript object is not guaranteed, one way to keep the order is to hold your keys in an array and then loop through the array.

new Vue({
  el: '#app',
  data: {
    keys: ['2', '1', '3'],
    obj: {
      "2": "BBB",
     "1": "AAA",
      "3":"CCC"
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <select>
     <option v-for="key in keys" :value="key">{{ obj[key] }}</option>
  </select>
  
    <select>
      <option value="3">C</option>
      <option value="1">A</option>
      <option value="2">B</option>
  </select>
</div>
Psidom
  • 209,562
  • 33
  • 339
  • 356