Need Help with Transform Map Script to Handle Blank Source Field

sanjeet1245
Tera Guru
  • I am trying to write a Run Script for a Transform Map in ServiceNow. The requirement is as follows:
  1. If the source.u_number field contains a blank value (""), the target field (e.g., number) should remain unchanged.
  2. If the source.u_number has a valid value (non-blank), it should update the target field with that value.

 

Here the script

 

answer = (function transformEntry(source) {

    

    if (source.u_number) {

        

        return source.u_number;

    } else {

       

        return undefined;

    }

})

(source);

 

The Problem: This script is not working as expected. When source.u_number is blank, it is still updating the target field with a blank value, which I don't want. The target field should remain unchanged in this case

2 REPLIES 2

Robbie
Kilo Patron
Kilo Patron

Hi @sanjeet1245,

 

This can easily be managed using a script similar to below.

The 'ignore = true' syntax essentially skips the record if the conditions are met, which in your case is when the number (source.u_number) is blank.

if (source.u_number === ''){
   ignore = true;
}

 To help others (and for me to gain recognition for my efforts), please mark this response correct by clicking on Accept as Solution and/or Kudos.





Thanks, Robbie

Justin Donath
Tera Contributor
Hey @sanjeet1245 , 
 
by just looking at your script and considering, this is a Field Map Source Script for mapping the u_number field (not the general "Run as" script), 
I recommend the following changes:
 
1) change your first condition to look like this:
 

 

if(source.u_number && source.u_number.trim() !== "")

 

 
This also checks for u_number beeing not a blank string (to handle cases where source.u_number might be " " instead of "")
 
2) If you want your target field to remain unchanged if the above condition fails, remove the else and just return the current target value 
 
So the resulting code should look like this:
 

 

answer = (function transformEntry(source, target) {
    if (source.u_number && source.u_number.trim() !== "") {
        return source.u_number;
    }
    return target.number;
})(source, target);

 

 
---
If this saved your day, hit that like button and make my day 🙂
If it works, accept this Solution or you will fail in your next promotion^^
Cheers