Vue.js sort Array Object by Key
There are many ways to sort array objects in JavaScript. Here in this tutorial, we are going to explain the easiest way to sort an array objects. You can also use our online editor to edit and run the code online.
Vue.js sort Array Object by Key Example
You can sort any object by key simply as below-
Example:
<div id="app"> <p>Unorderd Object = {{unorderdObj}}</p> <p>Ordered Object = {{orderedObj}}</p> <button @click="myFunction()">Click Me</button> </div> <script> new Vue({ el: '#app', data: { unorderdObj:{"c":"Apple", "d":"Mango","b": "Banana", "a":"Grapes"}, orderedObj:{} }, methods:{ myFunction: function () { this.orderedObj = this.sortObject(this.unorderdObj); }, sortObject: function(o) { return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {}); } } }); </script> |
If you run the above example it will sort the array by key.
Output of above example-
Advertisements