JavaScript循环提前终止问题:HL7转XML代码异常求助
Fix for HL7 FT1 to XML Conversion: Fixing Missing Entries & Loop Behavior Issues
Let's break down why your current code is causing those missing entry problems, then fix it up:
The Root Problem
Your code uses the loop variable i directly as the index for creating BillingCodeDTO segments in the target XML. Here's why that breaks:
- When you skip an entry (because
codelengthis null),istill increments. This means subsequent valid entries get assigned to higher, non-consecutive indices in thetmpstructure. Most XML parsers/serializers ignore these "gapped" indices, so only the first valid entry shows up (or none if the first skipped entry is the first one in scope). - The original logic ties the target index directly to the FT1 position, not the count of valid entries we actually want to keep.
Fixed Code
// Track the index of valid billing codes we're adding to the XML let validBillingCodeCount = 0; for(var i = 0; i < msg['FT1'].length(); i++) { // Keep your original business logic: only process FT1 entries beyond PR1's length if (i >= msg['PR1'].length()) { // Safely get the code value (optional chain prevents errors if fields are missing) const codelength = msg['FT1'][i]['FT1.7']['FT1.7.1']?.toString(); // Only create an entry if we have a valid code if (codelength) { // Use our valid entry counter as the index, not the loop variable i createSegment('BillingCodeDTO', tmp['Visit']['BillingCodes'], validBillingCodeCount); // Populate the Code value createSegment('Code', tmp['Visit']['BillingCodes']['BillingCodeDTO'][validBillingCodeCount])['@value'] = codelength; // Safely get and populate Quantity (with fallback to empty string if missing) const quantity = msg['FT1'][i]['FT1.10']['FT1.10.1']?.toString() || ''; createSegment('Quantity', tmp['Visit']['BillingCodes']['BillingCodeDTO'][validBillingCodeCount])['@value'] = quantity; // Only increment the counter when we actually add a valid entry validBillingCodeCount++; } } }
Key Changes Explained
- Separate Valid Entry Counter: We use
validBillingCodeCountinstead ofito index the target XML segments. This ensures valid entries are added in consecutive positions, no gaps, so all valid entries show up. - Safer Field Access: Added
?.optional chain operators to avoid runtime errors ifFT1.7orFT1.10segments/fields are missing from a message. - Fallback for Quantity: Added
|| ''to ensure we always have a value for Quantity, even if the source field is null/undefined. - Cleaner Logic: The counter only increments when we actually create a valid entry, so we don't waste positions on skipped null entries.
This will fix your issues:
- If the first eligible FT1 entry is null, no entries are created (correct behavior)
- If you have valid entries mixed with nulls, all valid entries will appear in order, no missing ones
内容的提问来源于stack exchange,提问作者Marc L
相关产品推荐
相关产品推荐

