Given the two javascript arrays produced by the vuetify table options.sortBy and sortDesc:
options.sortBy = ['name', 'email']; // fields to sort
options.sortDesc = [ false, true ]; // whether to sort field descending
Desired result:
sort = { $sort: { name: -1, email: 1 } };
So that we can push into mongodb aggregate pipeline array like:
pipeline.push(sort);
Code available in this branch.
It ends up being a good case for reduce. Here's what I ended up with:
type SortValue = 'asc' | 'desc' | 'ascending' | 'descending' | 1 | -1;
let sort:{[key:string]:SortValue} =
query.sortBy === undefined ||
query.sortDesc === undefined ? undefined :
query.sortBy.split(',').reduce((sort:{[key:string]:SortValue}, field:SortValue, index:number) => {
const sortDesc = query.sortDesc.split(',')[index];
const sortValue = !!(parseInt(sortDesc) || sortDesc === "true") ? 1 : -1;
sort[field] = sortValue;
return sort;
}, {});
pagination.sort = sort;
Open to improvements/variants. Thanks!
Code available in this branch.