Phoenix
Phoenix

Reputation: 21

VueJS2 sort JSON array

I am trying to sort a JSON array from JSON file a.json.

The array is coming like this:

{"data":
    [
      {"exception":"",
      "name":"Data Server1",
      "alias":"TOR-Server",
      "delayed":"NO",
      },
      {"exception":"",
      "name":"Data Server2",
      "alias":"FRA-Server",
      "delayed":"NO",
      }
    ]

I need to sort the data by the "alias name", coming from the JSON file with Vue JS.

This is my Javascript Code for the display in Vue JS

<script type="text/javascript">

    var app = new Vue({
    el: '#app',
    data: {
    json: null
    },

     computed: {

      sorted: function() {
            setTimeout(function() {
            var app = this.app.json
            if (app.length >= 6)
            return app;
              }, 5000);
            }
    },

    methods: {
        toggleClass(){
            if (this.failed == true){
                this.failed = false;    
            }
            else
            {
                this.failed = true; 
            }
        }
    }

But the Sorted function is not working and if I try to display the servers in the sorted array, I receive a blank page.

And my for loop in the HTML page is:

<div class="mainbutton" v-for="(server, index) in json.data ">

Hope this makes sense and I could get it working.

Upvotes: 2

Views: 4536

Answers (1)

Nisarg Shah
Nisarg Shah

Reputation: 14541

You can use Array.sort inside a computed, to return the sorted array.

For example, to sort the array's items by name property, you can call: this.json.sort((t1,t2) => t1.name < t2.name ? -1 : 1).

Here's a working snippet:

var app = new Vue({
  el: '#app',
  data: {
    json: [
      {
        "exception": "",
        "name": "Data Server3",
        "alias": "TOR-Server",
        "delayed": "NO",
      },
      {
        "exception": "",
        "name": "Data Server1",
        "alias": "TOR-Server",
        "delayed": "NO",
      },
      {
        "exception": "",
        "name": "Data Server2",
        "alias": "FRA-Server",
        "delayed": "NO",
      }
    ]

  },

  computed: {
    sortedJson: function() {
      return this.json.sort((t1,t2) => t1.name < t2.name ? -1 : 1);
    },
    sorted: function() {
      setTimeout(function() {
        var app = this.app.json
        if (app.length >= 6)
          return app;
      }, 5000);
    }
  },

  methods: {
    toggleClass() {
      if (this.failed == true) {
        this.failed = false;
      } else {
        this.failed = true;
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>

<div id="app">
  <div class="mainbutton" v-for="(server, index) in sortedJson ">
    {{server.name }}
  </div>
</div>

Upvotes: 1

Related Questions