How to process array of objects to get specific value ??

KM SN
Tera Expert

I am having the worknotes as shown below.

{"Name":"Mahesh","Response":"Approve","Comments":"SRR0074637, Rejected!"},
{"Name":"Gopi","Response":"Reject","Comments":"SRR0074637, Rejected!"} ]

I need to loop in to each object and whenever i found reject as a response i need to return corresponding comments from the above array.

how i need to do through script?

5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

@KM SN 

try this in background script

var worknotes = [
    {"Name": "Mahesh", "Response": "Approve", "Comments": "SRR0074637, Rejected!"},
    {"Name": "Gopi", "Response": "Reject", "Comments": "SRR0074637, Rejected!"}
];

function getRejectComments(worknotes) {
    for (var i = 0; i < worknotes.length; i++) {
        if (worknotes[i].Response === "Reject") {
            return worknotes[i].Comments;
        }
    }
    return null; // Return null if no reject response is found
}

var rejectComments = getRejectComments(worknotes);
gs.info('Reject Comments: ' + rejectComments);

Output:

AnkurBawiskar_0-1743081186001.png

 

If my response helped please mark it correct and close the thread so that it benefits future readers.

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

@KM SN 

Thank you for marking my response as helpful.

If my response helped please mark it correct and close the thread so that it benefits future readers.

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

Rohit  Singh
Mega Sage

Hi @KM SN 

 

You can use below code:

 

var workNotes = [
 { "Name": "Mahesh", "Response": "Approve", "Comments": "SRRO074637, Rejected." },
 { "Name": "Gopi", "Response": "Reject", "Comments": "SRR0074637, Rejected!" }
];
// Loop through the array
workNotes.forEach(entry => {
 // Check if the response is "Reject"
 if (entry.Response === "Reject") {
   // Print the corresponding comment
   gs.info(entry.Comments);
 }
});

 

If my response helped, please hit the Thumb Icon and accept the solution so that it benefits future readers.

Regards,
Rohit

 

Hi @KM SN ,

 

Please accept the solution as well and close the thread so that it benefit future readers as well.

 

Regards,

Rohit