1

I am using Vue2 and try to sort a v-for. I am iterating over an object and the vue-doc states:

When iterating over an object, the order is based on the key enumeration order of Object.keys(), which is not guaranteed to be consistent across JavaScript engine implementations.

My v-for without sorting looks like this:

<my-component :key="key + value + uid" 
v-for="(value,key) in myObject" :key-prop="key" 
:value-prop="value"></my-component>

How would I sort this if the Object.keys() are not consistent?

Edit: This is an example Object (returned from Rest-Service)

Chrome console logs this:

{
HUMID: "66%"
DAY: "true"
TEMP: "30"
}

The actual object is much larger.

Edit2:

With the help of "Oli Crt" I solved this. I wasn't able to calculate the sortedObjects as a computed property in my case, but I triggered it on getting the Response of my Rest-Service.

sortObject: function() {
    this.myObjectSorted =  Object.keys(this.myObject).sort();
}

This results in the following Object:

{
0: "DAY"
1: "HUMID"
2: "TEMP"
}

By taking the value of this sorted Object as my key-prop and getting the actual value (66%, true, 30) of the unsorted Object with

myObject[value]

I got the desired result.

<my-component :key="key + value + uid" 
v-for="(value,key) in myObjectSorted" :key-prop="value" 
:value-prop="myObject[value]"></my-component>
1stkeks
  • 25
  • 1
  • 7

1 Answers1

1

I think you should use a computed property.
You could sort the keys of your object

 computed: {
   myObjectSorted: function () {
     return Object.keys(this.myObject).sort(...); // Do your custom sorting here
   }
 }

Then use myObject[key] with the key from myObjectSorted in v-for.

Oli Crt
  • 954
  • 1
  • 9
  • 9