Mirth Connect Channel destination sort JSON array of objects

Viewed 722

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

2 Answers

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));

Sorting can be done, using Array.sort. And can update data

let data = {
  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
          }
        }
      }
    ]
  }
};
data.Set.ArrayToSort = data.Set.ArrayToSort.sort((x, y) => x.Num - y.Num);
console.log(JSON.stringify(data, null, 2));

Related