Vue.js sort Array Object by Key Example

Vue.Js

Nicesnippets

175

22-08-2020


Hi Guys,

In this example, I will describe you how to sort Array Object by Key in Vue.js. we will show example of 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.

Here, I will give you full example for simply sort Array Object by Key in Vue js as bellow.

Script Code

<script>

new Vue({

el: '#app',

data: {

unorderdObj:{"c":"PHP", "d":"Laravel","b": "Html", "a":"Css"},

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>

Full Code

<!DOCTYPE html>

<html>

<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

</head>

<body>

<div id="app">

<p>Unsort Object = {{unorderdObj}}</p>

<p>Short Object = {{orderedObj}}</p>

<button @click="myFunction()">Click Me</button>

</div>

<script>

new Vue({

el: '#app',

data: {

unorderdObj:{"c":"PHP", "d":"Laravel","b": "Html", "a":"Css"},

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>

</body>

</html>

It Will help you...


Recommended Posts