Mirth (NextGen) Connect Bits #1: Looping & Deleting Segments

[UPDATED] : Fixed the delete logic since I found issues on it. Loop will start at the bottom or last child instead.

A quick rundown on how to loop and delete specific segments based on some conditions. Here I want to check all OBX segments and delete those that have a value of “ED” in OBX.2.1 and “PDF” in OBX.3.1. I usually add this code in the Source->Transformer.

for(var i = msg.children().length() - 1; i >= 0; i--) {
    if(msg.children()[i].name().toString() == 'OBX') {
        if(msg.children()[i]['OBX.2']['OBX.2.1'].toString() == 'ED' && msg.children()[i]['OBX.3']['OBX.3.1'].toString() == 'PDF') {
            delete msg.children()[i];

Let’s break down the code and the behavior.

  • msg.children().length() would get the total number of child nodes the msg object has.
  • In the for loop, we track down the position or index of that child using the variable i.
  • Using the .name() method, we get the child node’s name, at this level, that would be the segment name.
  • We then use an if statement to check what segment we are, and set a specific behavior when that segment is found. In this case, we’re looking for the OBXs.
  • We then use another set of if statement, but combining the .children() and the i variable as the index to select the child node. We then added hardcoded property names [‘OBX.2’] and [‘OBX.2.1’] and [‘OBX.3’] and [‘OBX.3.1’] where we are expecting values to check. The .toString() method would convert the value of the node to a string.
  • If the conditions were met, we delete the child node using the statement delete msg.children()[i].

For more Mirth Connect related blog posts, check out the Mirth (NextGen) Bits tag or Health IT page. Feel free to leave a comment or feedback.

That’s about it. I hope that helps.


Add a Comment

Your email address will not be published. Required fields are marked *