To handle the scenario where the OBX.5.1 field contains multiple entries separated by backticks (```), you can split the field content into individual drugs and map them accordingly. Below is an updated approach to achieve your desired JSON structure:
Revised Code
var drg = -1;
for each (seg in msg..OBX) {
// Check if OBX.2.1 equals "CE"
var obx2_1 = seg['OBX.2']['OBX.2.1'].toString();
if (obx2_1.match(/CE/)) {
// Get the OBX.5.1 value and split it by backticks
var drugList = seg['OBX.5']['OBX.5.1'].toString();
if (drugList != "NONE") {
var drugs = drugList.split('`'); // Split by backtick to get individual drugs
for each (drugName in drugs) {
drg++;
tmp['order']['drugs'][drg] = {};
var drug = tmp['order']['drugs'][drg];
drug['drugName'] = drugName.trim(); // Trim to remove extra spaces
}
}
}
// Handle "SpecInstruc" case (if needed)
if (obx2_1.toString() == "SpecInstruc") {
tmp['order']['comments'] = seg['OBX.5']['OBX.5.1'].toString();
}
}
Explanation
Extract OBX.2.1:
Use seg['OBX.2']['OBX.2.1'].toString() to check if the segment type is CE.
Split OBX.5.1:
Use split('')` to break the string into individual drug names based on the backtick delimiter.
Iterate Over Drugs:
Loop through the resulting array of drug names and add each one as a new entry in the order['drugs'] array.
Trim Drug Names:
Use trim() to ensure there are no leading or trailing spaces in the drug names.
Variable Number of Drugs and OBX Segments:
The split function dynamically handles any number of drugs in OBX.5.1.
The outer loop processes all OBX segments, allowing for multiple segments with drug lists.