Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Need help to combine 2 arrays if one of them is empty or variable being used in array does not exist

GD11
Tera Expert

I have a variable set attached to 1 catalog item and there is flow designer that is integrated with othe 3rd party for 2 catalog items. i have variable which might have value for that variable set sometime but sometime it might be empty. so the code is failing to concatenate both arrays of both MRVS if 2nd one is empyt or is not present in catalog item because it is being shown based on need using UI policy. please advase what should we do to combine both arryas if MRVSJSON1 is empty or undefined in below code. right now flow designer is throwing inexpected error if we have mrvsjson1 as empty or not present in catalog item because of which payload is not getting sent over for 1st MRVS even if it has a value.

 

 

var mrvsJson = task.request_item.variables.ordervariable1;
var parsedData = JSON.parse(mrvsJson);
var arr = [];

for (var i = 0; i < parsedData.length; i++) {
    var obj = {};
    obj["Part"] = parsedData[i].part; // field name for part
    obj["Qty"] = parsedData[i].quantity; // field name for quantity
    arr.push(obj);
}
//gs.info('Value of MRVS ordervariable1: ' + JSON.stringify(arr));

// Get second MRVS (request_standalone_monitor)

var mrvsJson1 = task.request_item.variables.request_standalone_monitor;
var arr1 = [];
gs.info('value of the stand alone monitor 1 ' + mrvsJson1);
mrvsJson1 = String(mrvsJson1);
if(mrvsJson1 && mrvsJson1 != undefined){
gs.info('value of the stand alone monitor 2 ' + mrvsJson1);
//parsedData1 = JSON.stringify(parsedData1);

var parsedData1 = JSON.parse(mrvsJson1);
for (var j = 0; j < parsedData1.length; j++) {
    var obj1 = {};
    obj1["Part"] = parsedData1[j].part1; // field name for part
    obj1["Qty"] = parsedData1[j].qty; // field name for quantity
    arr1.push(obj1);
}
//gs.info('Value of MRVS request_standalone_monitor: ' + JSON.stringify(arr1));
arr1 = JSON.stringify(arr1);

} else {
    arr1 = JSON.stringify(arr);
}
// Combine both arrays
var combinedArr = arr.concat(arr1);

// Assign combined array to source_variables
source_variables['OrderVariable1'] = JSON.stringify(combinedArr);

gs.info('Final combined OrderVariable1: ' + source_variables['OrderVariable1']);
 
               
1 ACCEPTED SOLUTION

@GD11 

can you give me your business requirement and explain in detail what's required?

I assume this is what you want

-> 2nd MRVS or 1st MRVS if empty should not be appended

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

12 REPLIES 12

@GD11 

your script is big enough and we don't have access to your instance

what debugging did you do?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

HI @Ankur Bawiskar whole script was working fine till we added addtinal monitor mrvs, it also works using my code whenever there is value in additional monitor, but it does not work if that 2nd MRVS variable is not there on catalog item.  also other part of script is fine, its only MRVS part that needs help with added. below is the script that works if both MRVS are present on catalog item byt it fails if 2nd is not there. it is not passwing value to Ordervariable1 , please help.

 

(function execute(inputs, outputs) {
var body = {};
var all_comments = [];
var all_worknotes = [];
var all_attachments = [];
var source_info = {};
var source_contact = {};
var source_variables = {};
var varValueArray = [];
var varValue;
var OrderVariable1 = {};

// Capture all the comment information on ticket
var comments = new GlideRecord('sys_journal_field');
comments.addQuery('element', 'comments');
comments.addQuery('element_id', inputs.task_id);
comments.addQuery('sys_created_by', 'DOES NOT CONTAIN', 'insight');
comments.query();
while (comments.next()) {
var comment = {};
comment.value = comments.value.toString();
comment.time = comments.sys_created_on.toString();
comment.created_by = comments.sys_created_by.toString();
all_comments.push(comment);
}

// Capture all the work note information on ticket
var work_notes = new GlideRecord('sys_journal_field');
work_notes.addQuery('element', 'work_notes');
work_notes.addQuery('element_id', inputs.task_id);
work_notes.addQuery('sys_created_by', 'DOES NOT CONTAIN', 'insight');
work_notes.query();
while (work_notes.next()) {
var worknote = {};
worknote.value = work_notes.value.toString();
worknote.time = work_notes.sys_created_on.toString();
worknote.created_by = work_notes.sys_created_by.toString();
all_worknotes.push(worknote);
}

// Add comments and work notes to the body
body.comments = all_comments;
body.work_notes = all_worknotes;

// Add in mandatory fields to the body
body.description = checkForNull(inputs.description);
body.short_description = checkForNull(inputs.short_description);
body.correlation_id = checkForNull(inputs.correlation_id);
body.correlation_display = checkForNull(inputs.correlation_display);
body.sys_id = checkForNull(inputs.integrated);

function checkForNull(inputs) {
if (inputs != null || inputs != undefined) {
return inputs.toString();
} else {
return '';
}
}

// Capture all attachments associated to this ticket
var attachment = new GlideSysAttachment();
var agr = attachment.getAttachments('sc_task', inputs.task_id);
while (agr.next()) {
var attachment_body = {};
attachment_body.attachment_name = agr.file_name.toString();
attachment_body.attachment_type = agr.content_type.toString();
attachment_body.attachment_content = attachment.getContentBase64(agr);
all_attachments.push(attachment_body);
}
body.attachments = all_attachments;

// Populates the source_info, source_contact and source_variables objects
var task = new GlideRecord('sc_task');
task.addQuery('sys_id', inputs.task_id);
task.query();
if (task.next()) {
source_info.number = task.number.toString();
source_info.raised_by = task.sys_created_by.toString();
source_info.priority = task.priority.toString();
source_info.ritm = task.request_item.number.toString();
source_contact.name = task.opened_by.name.toString();
source_contact.email = task.opened_by.email.toString();
source_contact.phone = task.opened_by.mobile_phone.toString();

// Collects the variable data from the RITM ticket. Works for Variables and variable sets
var question_answers = new GlideRecord('sc_item_option_mtom');
question_answers.addQuery('request_item', task.request_item.sys_id.toString());
question_answers.orderBy('sc_item_option.order');
question_answers.query();
while (question_answers.next()) {
var varName = question_answers.sc_item_option.item_option_new.name;

if (question_answers.sc_item_option.item_option_new.type == '8') { // 8 = reference
varValue = getReferenceValue(question_answers.sc_item_option.item_option_new.reference, question_answers.sc_item_option.value);
} else if (question_answers.sc_item_option.item_option_new.type == '21') { // 21 = List Collector
if (question_answers.sc_item_option.value != '') {
var list = question_answers.sc_item_option.value.split(",");
for (i = 0; i < list.length; i++) {
if (i == 0) {
varValueArray.push(getReferenceValue(question_answers.sc_item_option.item_option_new.list_table, list[i]));
} else {
varValueArray.push(' ' + getReferenceValue(question_answers.sc_item_option.item_option_new.list_table, list[i]));
}
}
varValue = varValueArray.toString();
} else {
varValue = '';
}
} else if (question_answers.sc_item_option.item_option_new.type == '18') { // 18 = Lookup Select Box
varValue = getReferenceValue(question_answers.sc_item_option.item_option_new.lookup_table, question_answers.sc_item_option.value);
} else {
varValue = question_answers.sc_item_option.value.getDisplayValue();
}

if (varName != "" && varValue != "") {
source_variables[varName] = varValue;
// gs.info('name of field ' + varName + ' and value ' + varValue);
}
}

// Get first MRVS (ordervariable1)
var mrvsJson = task.request_item.variables.ordervariable1;
var parsedData = JSON.parse(mrvsJson);
var arr = [];

for (var i = 0; i < parsedData.length; i++) {
var obj = {};
obj["Part"] = parsedData[i].part; // field name for part
obj["Qty"] = parsedData[i].quantity; // field name for quantity
arr.push(obj);
}
//gs.info('Value of MRVS ordervariable1: ' + JSON.stringify(arr));

// Get second MRVS (request_standalone_monitor)
gs.info('value of the stand alone monitor ' + task.request_item.variables.request_standalone_monitor);
if(task.request_item.variables.request_standalone_monitor != null && task.request_item.variables.request_standalone_monitor != '' ){
var mrvsJson1 = task.request_item.variables.request_standalone_monitor;
var parsedData1 = JSON.parse(mrvsJson1);
var arr1 = [];

for (var j = 0; j < parsedData1.length; j++) {
var obj1 = {};
obj1["Part"] = parsedData1[j].part1; // field name for part
obj1["Qty"] = parsedData1[j].qty; // field name for quantity
arr1.push(obj1);
}
//gs.info('Value of MRVS request_standalone_monitor: ' + JSON.stringify(arr1));

// Combine both arrays
var combinedArr = arr.concat(arr1);

// Assign combined array to source_variables
source_variables['OrderVariable1'] = JSON.stringify(combinedArr);
} else{
source_variables['OrderVariable1'] = JSON.stringify(arr);
}


//gs.info('Final combined OrderVariable1: ' + source_variables['OrderVariable1']);

}

function getReferenceValue(table, sys_id) {
var gr = new GlideRecord(table);
gr.get(sys_id);
return gr.getDisplayValue();
}

body.source_variables = source_variables;
body.source_info = source_info;
body.source_contact = source_contact;
outputs.body = JSON.stringify(body);
gs.info('value of output ' + outputs.body);
})(inputs, outputs);

@GD11 

try this

(function execute(inputs, outputs) {
    var body = {};
    var all_comments = [];
    var all_worknotes = [];
    var all_attachments = [];
    var source_info = {};
    var source_contact = {};
    var source_variables = {};
    var varValueArray = [];
    var varValue;
    var OrderVariable1 = {};

    // Capture all the comment information on ticket
    var comments = new GlideRecord('sys_journal_field');
    comments.addQuery('element', 'comments');
    comments.addQuery('element_id', inputs.task_id);
    comments.addQuery('sys_created_by', 'DOES NOT CONTAIN', 'insight');
    comments.query();
    while (comments.next()) {
        var comment = {};
        comment.value = comments.value.toString();
        comment.time = comments.sys_created_on.toString();
        comment.created_by = comments.sys_created_by.toString();
        all_comments.push(comment);
    }

    // Capture all the work note information on ticket
    var work_notes = new GlideRecord('sys_journal_field');
    work_notes.addQuery('element', 'work_notes');
    work_notes.addQuery('element_id', inputs.task_id);
    work_notes.addQuery('sys_created_by', 'DOES NOT CONTAIN', 'insight');
    work_notes.query();
    while (work_notes.next()) {
        var worknote = {};
        worknote.value = work_notes.value.toString();
        worknote.time = work_notes.sys_created_on.toString();
        worknote.created_by = work_notes.sys_created_by.toString();
        all_worknotes.push(worknote);
    }

    // Add comments and work notes to the body
    body.comments = all_comments;
    body.work_notes = all_worknotes;

    // Add in mandatory fields to the body
    body.description = checkForNull(inputs.description);
    body.short_description = checkForNull(inputs.short_description);
    body.correlation_id = checkForNull(inputs.correlation_id);
    body.correlation_display = checkForNull(inputs.correlation_display);
    body.sys_id = checkForNull(inputs.integrated);

    function checkForNull(inputs) {
        if (inputs != null && inputs != undefined) {
            return inputs.toString();
        } else {
            return '';
        }
    }

    // Capture all attachments associated to this ticket
    var attachment = new GlideSysAttachment();
    var agr = attachment.getAttachments('sc_task', inputs.task_id);
    while (agr.next()) {
        var attachment_body = {};
        attachment_body.attachment_name = agr.file_name.toString();
        attachment_body.attachment_type = agr.content_type.toString();
        attachment_body.attachment_content = attachment.getContentBase64(agr);
        all_attachments.push(attachment_body);
    }
    body.attachments = all_attachments;

    // Populates the source_info, source_contact and source_variables objects
    var task = new GlideRecord('sc_task');
    task.addQuery('sys_id', inputs.task_id);
    task.query();
    if (task.next()) {
        source_info.number = task.number.toString();
        source_info.raised_by = task.sys_created_by.toString();
        source_info.priority = task.priority.toString();
        source_info.ritm = task.request_item.number.toString();
        source_contact.name = task.opened_by.name.toString();
        source_contact.email = task.opened_by.email.toString();
        source_contact.phone = task.opened_by.mobile_phone.toString();

        // Collects the variable data from the RITM ticket. Works for Variables and variable sets
        var question_answers = new GlideRecord('sc_item_option_mtom');
        question_answers.addQuery('request_item', task.request_item.sys_id.toString());
        question_answers.orderBy('sc_item_option.order');
        question_answers.query();
        while (question_answers.next()) {
            var varName = question_answers.sc_item_option.item_option_new.name;

            if (question_answers.sc_item_option.item_option_new.type == '8') { // 8 = reference
                varValue = getReferenceValue(question_answers.sc_item_option.item_option_new.reference, question_answers.sc_item_option.value);
            } else if (question_answers.sc_item_option.item_option_new.type == '21') { // 21 = List Collector
                if (question_answers.sc_item_option.value != '') {
                    var list = question_answers.sc_item_option.value.split(",");
                    for (i = 0; i < list.length; i++) {
                        if (i == 0) {
                            varValueArray.push(getReferenceValue(question_answers.sc_item_option.item_option_new.list_table, list[i]));
                        } else {
                            varValueArray.push(' ' + getReferenceValue(question_answers.sc_item_option.item_option_new.list_table, list[i]));
                        }
                    }
                    varValue = varValueArray.toString();
                } else {
                    varValue = '';
                }
            } else if (question_answers.sc_item_option.item_option_new.type == '18') { // 18 = Lookup Select Box
                varValue = getReferenceValue(question_answers.sc_item_option.item_option_new.lookup_table, question_answers.sc_item_option.value);
            } else {
                varValue = question_answers.sc_item_option.value.getDisplayValue();
            }

            if (varName != "" && varValue != "") {
                source_variables[varName] = varValue;
            }
        }

        // Get first MRVS (ordervariable1)
        var arr = [];
        var mrvsJson = task.request_item.variables.ordervariable1;
        if (mrvsJson && mrvsJson != '') {
            try {
                var parsedData = JSON.parse(mrvsJson);
                for (var i = 0; i < parsedData.length; i++) {
                    var obj = {};
                    obj["Part"] = parsedData[i].part;
                    obj["Qty"] = parsedData[i].quantity;
                    arr.push(obj);
                }
            } catch (e) {
                gs.info('Error parsing ordervariable1: ' + e);
            }
        }

        // Get second MRVS (request_standalone_monitor)
        var arr1 = [];
        var mrvsJson1 = task.request_item.variables.request_standalone_monitor;
        if (mrvsJson1 && mrvsJson1 != '') {
            try {
                var parsedData1 = JSON.parse(mrvsJson1);
                for (var j = 0; j < parsedData1.length; j++) {
                    var obj1 = {};
                    obj1["Part"] = parsedData1[j].part1;
                    obj1["Qty"] = parsedData1[j].qty;
                    arr1.push(obj1);
                }
            } catch (e) {
                gs.info('Error parsing request_standalone_monitor: ' + e);
            }
        }

        // Combine both arrays
        var combinedArr = arr.concat(arr1);
        source_variables['OrderVariable1'] = JSON.stringify(combinedArr);

    }

    function getReferenceValue(table, sys_id) {
        var gr = new GlideRecord(table);
        gr.get(sys_id);
        return gr.getDisplayValue();
    }

    body.source_variables = source_variables;
    body.source_info = source_info;
    body.source_contact = source_contact;
    outputs.body = JSON.stringify(body);
    gs.info('value of output ' + outputs.body);
})(inputs, outputs);

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

HI @Ankur Bawiskar  this is also returing empty value for ordervariable1 , tried debugging and adding logs changing code but no luck , please help

@GD11 

can you give me your business requirement and explain in detail what's required?

I assume this is what you want

-> 2nd MRVS or 1st MRVS if empty should not be appended

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader