問題の核心は、コードが OBR と OBX セグメントが常にペアで表示されると想定していることです。
OBR|1|...
OBX|1|...
OBR|2|...
OBX|1|...
OBR|3|...
OBX|1|...
ただし、OBR セグメントと OBX セグメントの数が一致しない場合、または厳密に交互に表示されない場合に遭遇するとすぐに、事態は悪化し始めます。
OBR|1|... oh oh, this obr is followed by two obx segments
OBX|1|...
OBX|2|...
OBR|2|... oh oh, this obr isn't followed by an obx segment at all.
OBR|3|...
OBX|1|...
最初に、次のコード行の意味を理解する必要があります。
var obrSegments = msg['OBR'];
var obxSegments = msg['OBX'];
この例では、obrSegments は、ご想像のとおり、obr セグメントの配列です。同様に、obxSegments は obxSegments の配列です。これらの配列はどちらも、obr セグメントに対して obx セグメントがどのように配置されているかを認識して構築されていません。
メッセージ内の obr セグメントと obx セグメントが常に厳密に交互に表示されることを保証できる場合は、obrSegments[i] と obxSegments[i] が常に連続していることを保証できます。
一方、obr と obx セグメントの数が同一でない場合、または数が同一であっても、セグメントが厳密に交互に表示されない場合、obrSegments[i] が一致するという保証はありません。すぐに obxSegments[i] が続きます。
あなたの質問の言い回しは 100% 明確ではありません。しかし、OBR の内容を調べるときはいつでも、その直後に続くすべての obx セグメントの内容を条件付きで変更したいと思うでしょう。
このようなものをもっとお勧めします。
var obrSegments = msg['OBR'];
// iterate through the OBR segments
for each (var obr in obrSegments) {
// extract the field components that you need from this OBR
// don't assume I've done this correctly. The text of your
// question didn't match your example code, so I don't exactly know what you need
var OBR4_1 = obr['OBR.4']['OBR.4.1'];
var OBR4_2 = obr['OBR.4']['OBR.4.2'];
// now iterate through the OBX segments that immediately follow this OBR.
// This is a bit tricky to do, but here's how I approach the problem
// you need an XML list of all the segments, not just the current OBR
var segments = obr.parent().children();
// you need to know the current OBR's index in the segments list
var obrIndex = obr.childIndex();
// theoretically, at this point, obr should refer to exactly the same
// data as segments[obrIndex]
// to do the actual OBX iteration:
var nextIndex = obrIndex + 1;
while (nextIndex < segments.length()) {
var nextSegment = segments[nextIndex];
var nextSegmentType = nextSegment.localName();
if (nextSegmentType == 'OBX') {
var obx = nextSegment;
// Bearing in mind that I haven't tested this code and have just been spewing it
// off into my web browser,
// you can now be confident that variable obx refers to one of the obx
// segments immediately following variable obr.
if (OBR4_1 == blah blah blah) {
obx['OBX.5']['OBX.5.1'] = blah blah blah;
obx['OBX.5']['OBX.5.2'] = blah blah blah;
}
else {
// looks like we've finished processing all the OBX segments for the current
// obr, time to break out of the inner loop.
break;
}
++nextIndex;
}
}