Search code examples
javascriptjsonmirth

Mirth Connect Channel destination sort JSON array of objects


I need to sort an array of objects being sent into Mirth. Originally the sorting was done via XSLT (since the inbound data was XML), but with a change (outside of my control) the inbound data was changed to JSON. The original sorting was being done in a destination transformation which I have kept.

Inbound JSON example:

{
  "Id":"100001",
  "Set":
  {
    "unimportantdata1":null,
    "unimportantdata2":null,
    "unimportantdata3":"0001-01-01T00:00:00",
    "unimportantdata4":"0001-01-01T00:00:00",
    "ArrayToSort":[
      {
        "vt":"blah",
        "Num":"2",
        "desc":"dp",
        "Value":["1.1","1.2"],
        "Time":"2020-03-23T02:23:41",
        "blah": { "Name": { "LastName":"ob-ln","Firstname":"ob-fn","MiddleName":"ob-mi","Title":null}}
      },
      {
        "vt":"yadda",
        "Num":"1",
        "desc":"dp",
        "Value":["1.1","1.2"],
        "Time":"2020-03-23T02:23:41",
        "blah": { "Name":{"LastName":"ob-ln","Firstname":"ob-fn","MiddleName":"ob-mi","Title":null}}
      }
   ]}
}

I need the ArrayToSort ordered by the "Num" property ascending.

My questions are:

  1. Is the best place to sort this in the destination channel transformer?
  2. I'm guessing the way to go is via JavaScript, but I'm unsure how to proceed -- suggestions?

Thank you in advance


Solution

  • Turns out the solution is pretty simple.

    In JavaScript, you just need to do the following:

    msg['Set']['ArrayToSort'].sort(function(a,b){
        return a["Num"] - b["Num"];
    });
    
    logger.info(JSON.stringify(msg));