Good day,

while creating express middleware components using the AppDevPack and domino-db I came across the need to sort a resulting JSON object by one of its attributes:


In the following sample, I wanted to sort the object by the "position" attribute in my node/express app.



var design_docs = {[

{

"headerName"
: "erstellt",
"field"
: "$20",
"position"
: 1,
"rowGroup"
: false,
"icon"
: false,
"sortable"
: true
},

{

"headerName"
: "letzte Änderung",
"field"
: "$22",
"position"
: 2,
"rowGroup"
: false,
"icon"
: false,
"sortable"
: true
},

{

"headerName"
: "Maske",
"field"
: "Form",
"position"
: 3,
"rowGroup"
: false,
"icon"
: false,
"sortable"
: true
},

{

"headerName"
: "Akentz.",
"field"
: "$26",
"position"
: 4,
"rowGroup"
: false,
"icon"
: false,
"sortable"
: true
},

{

"headerName"
: "Typ",
"field"
: "$27",
"position"
: 5,
"rowGroup"
: false,
"icon"
: false,
"sortable"
: false
},

{

"headerName"
: "Bearbeiter",
"field"
: "$15",
"position"
: 6,
"rowGroup"
: false,
"icon"
: false,
"sortable"
: true
},

{

"headerName"
: "Betreff",
"field"
: "subject",
"position"
: 7,
"rowGroup"
: false,
"icon"
: false,
"sortable"
: false
}

]}



After some googleing around, I came across a very nice option to do that using loadsh - so check this out in case you need it at some point:


https://www.npmjs.com/package/lodash

To install using npm use:


npm i --save lodash


First,. let's import lodash:


var
_ = require('lodash');

Next, wie will pick the "orderBy" function for sorting:



var
orderBy = require('lodash/orderBy');

Now, let's sort our object in ascending order:


var
sorted_asc = orderBy(design_docs,'position');

To change that to descending order we simply add:


var
sorted_desc = orderBy(design_docs,'position').reverse();

Done ! This works on all data types I tested (date-time, numbers, strings, booleans).


Happy coding !


Heiko.

Heiko Voigt   |   5 November 2019 12:32:37   |    domino-db  NERD  Node.js  JavaScript    |  
  |   Next Document   |   Previous Document

Discussion for this entry is now closed.

Comments (0)

No Comments Found