Monday, 21 October 2019

Sorting my API data numerically (0-9) in VueJS

I have data mapped from an API (see below) which I am reaching fine but I am looking at sorting it numerically (0-9). I'm having a hard time doing this with Vue. If I had my data static in the data(){...}, I can get it done a number of ways. But not from an API because I can't point to the API for some reason whenever I try to point to it from a function in my methods. I have no idea what is going on and I'm hoping you guys have some direction.

The template - Because of the nesting of the API, I am nesting loops as well. (maybe there is a better way to also do this. I'm all ears). allBatches is my Getter. I am serving the API through my State Manager (Vuex)

<div>
  <div v-for="batches in allBatches" :key="batches.id">
     <div 
        v-for="dispatchstation in batches.dispatchstation" 
        :key="dispatchstation.id">
        <div v-for="apps in dispatchstation.applications" :key="apps.id">
          <div></div>
        </div>
     </div>
  </div>
</div>

The data structure in the API - I intentionally left unrelated data out. There are other layers in between. But this shows the path I am looping and reaching out to.

"batches": [
{
  "dispatchstation": [
    {
      "applications": [
        "384752387450",
        "456345634563",
        "345634563456",
        "567845362334",
        "567456745677",
        "456734562457",
        "789676545365",
        "456456445556",
        "224563456345",
        "456878656467",
        "053452345344",
        "045440545455",
        "045454545204",
        "000014546546",
        "032116876846",
        "546521302151",
        "035649874877",
        "986765151231",
        "653468463854",
        "653853121324",
        "000145456555"
      ]
    }
  ]
}

],

I've tried to do this with lodash using _.orderBy and use it a pipe. No luck. And I also tried this:

data() {
  return {
    sortAsc: true,
    sortApps: "" // see explanation
  };
},
computed: {
  ...mapGetters(["allBatches"]),
  sortedData() {
    let result = this.sortApps;

    let ascDesc = this.sortAsc ? 1 : -1;
    return result.sort(
      (a, b) => ascDesc * a.applications.localeCompare(b.applications)
    );
  }
},

I used (tried) this method by giving sortApps the loop criteria dispatchstations.applications and loop v-for='apps in sortedData'. I'm sure that is wrong. Vue is not really my forte.

I really don't have any preference on how this should be as long as the data renders sorted out numerically ASC.

Any thoughts?

Thanks

EDIT

Using Chase's answer, I am still getting the data through but it doesn't display. I had to remove the negation (!).

Mutation and getters of State view from the vue chrome tool

Mutation of State view from the vue chrome tool

enter image description here



from Sorting my API data numerically (0-9) in VueJS

No comments:

Post a Comment