Using a variable as a search value within a filter function of API Response to set a variable

I am trying to use the following snippet to filter an API response body while utilizing a variable as the search value (ObjectID):

var data = JSON.parse(responseBody);
postman.setEnvironmentVariable(“ReportID”, data.filter(function(column) {
return column.ObjectID===(pm.environment.get(“ObjectID”));
})[0].ReportID);

I have gotten it to work once, and now it returns an error of “There was an error in evaluating the test script: TypeError: Cannot read property ‘ReportID’ of undefined.”

I am able to get a similar request to work when I utilize a hard coded search value (Administrators):

var data = JSON.parse(responseBody);
pm.environment.set(“RoleID”, data.filter(function(column) {
return column.Name===“Administrators”;
})[0].ID);

Is there an easier way to set a variable from a filter function of an API response?

@Jeremy.green The error message indicates that the filter returned an empty array, as no array elements could be matched by your condition. A slightly cleaner way to write this is as follows:

var targetId = pm.environment.get('ObjectID'),
    firstMatch = pm.response.json().find((column) => { return column.Name === targetId; });

firstMatch ? pm.environment.set('RoleID', firstMatch) : console.warn(`No matches found for ${targetId}`);
1 Like

@kunagpal I am having issues using the snippet in your response. Maybe if I explain it a little better:

ObjectID is a constant across all our environments, and I am trying to use the ObjectID as a variable to find the corresponding ReportID (Guid) that changes between environments. Below is part of the response I am trying to search:

[
{
“ObjectID”: 1101,
“Name”: “Schedules”,
“TypeName”: “Place”,
“TypeID”: 2,
“ParentID”: 1000,
“ModuleID”: 1000,
“HelpLink”: “View all existing schedules.”,
“HelpID”: “115007895267”,
“Navigation”: true,
“ProductID”: null,
“ProductType”: null,
“ReportID”: null,
“ParentObject”: null
},
{
“ObjectID”: 1102,
“Name”: “Saved Reports”,
“TypeName”: “Place”,
“TypeID”: 2,
“ParentID”: 1000,
“ModuleID”: 1000,
“HelpLink”: “View all existing saved reports.”,
“HelpID”: “115008053768”,
“Navigation”: true,
“ProductID”: null,
“ProductType”: null,
“ReportID”: null,
“ParentObject”: null
},
{
“ObjectID”: 1200,
“Name”: “Signature Log”,
“TypeName”: “Report”,
“TypeID”: 3,
“ParentID”: 1000,
“ModuleID”: 1000,
“HelpLink”: “View all reports that have been signed by users.”,
“HelpID”: null,
“Navigation”: true,
“ProductID”: null,
“ProductType”: null,
“ReportID”: “6410f5bc-6773-443a-b210-8b258671aea4”,
“ParentObject”: null
},

Thanks @kunagpal I was able to slightly modify your snippet, and it is working for me now! It seems as if there is an issue to call for a variable within a data.filter() function. As long as I call for the variable before, then utilize said called value, it seems to work as expected. Thanks for your time!