0

I have a json object list (carriers) like this:

json data

In my *.vue I render this with:

<tr v-for="carrier in this.carriers">
   <td>{{ carrier.id }}</td> ....

My thead / th's can be clicked for sorting the table like this:

<thead>
   <tr>
      <th class="pointer link" @click="sort('id')">
         ID
         <span v-if="'id' === currentSortCol">
            {{currentSortDir ==='asc' ? '&#8593;':'&#8595;'}}
         </span>
      </th>
      <th class="pointer link" @click="sort('region.name')">
         Region
         <span v-if="'region.name' === currentSortCol">
            {{currentSortDir ==='asc' ? '&#8593;':'&#8595;'}}
         </span>
      </th>....

and my sort method is like this:

        sort(col) {
            if (this.currentSortCol === col) {
                this.currentSortDir = this.currentSortDir === "asc" ? "desc" : "asc";
            } else {
                this.currentSortCol = col;
            }
            this.carriers.sort(this.sortBy(col, this.currentSortDir));
        },
        sortBy(property, order) {
            this.currnetSortDir=order;
            return function(a, b) {
                const varA =
                    typeof a[property] === "string"
                        ? a[property].toUpperCase()
                        : a[property];
                const varB =
                    typeof b[property] === "string"
                        ? b[property].toUpperCase()
                        : b[property];

                let comparison = 0;
                if (varA > varB) comparison = 1;
                else if (varA < varB) comparison = -1;
                return order === "desc" ? comparison * -1 : comparison;
            };
        }

Problem: The sorting asc, desc is fine with the ID (carrier.id) . But it will not sort the nesting carrier.region.name column. How can I sort a nesting column, like this carrier.region.name?

1 Answer 1

1

You should use something like 'get' method from lodash package in order to get nested props:

import _get from 'lodash/get'
...
const propValueA = _get(a, property);
const propValueB = _get(b, property);
const varA = typeof propValueA === "string" ? propValueA.toUpperCase() : propValueA;
const varB = typeof propValueB === "string" ? propValueB.toUpperCase() : propValueB;
Sign up to request clarification or add additional context in comments.

1 Comment

const propValueA = _get(a, property); const propValueB = _get(b, property); const varA = typeof propValueA === "string" ? propValueA.toUpperCase() : propValueA; const varB = typeof propValueB === "string" ? propValueB.toUpperCase() : propValueB; -- will work. can you update your answer, then I will accept it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.