How to select a specific string value with a condition as new variable?

I am writing a test that needs to find a line that has the “Square” in the “name” and set the “id” of the array that has that line as the new variable “departmentID”.

Response body

{
    "id": 1000000019,
    "name": "Exquisite",
    "city": "not important",
    "address": "not important",
    "tel": "not important"
},
{
    "id": 1000000006,
    "name": "Blue Square",
    "city": "not important",
    "address": "not important",
    "tel": "not important"
},
{
    "id": 1000000018,
    "name": "Big House",
    "city": "not important",
    "address": "not important",
    "tel": "not important"
}

Hey @illusorydannyboy,

Welcome to the community! :wave:

I’m not sure if that’s the complete response body or not, I would expect those objects to be wrapped in an array.

If it looked like this:

[
	{
	    "id": 1000000019,
	    "name": "Exquisite",
	    "city": "not important",
	    "address": "not important",
	    "tel": "not important"
	},
	{
	    "id": 1000000006,
	    "name": "Blue Square",
	    "city": "not important",
	    "address": "not important",
	    "tel": "not important"
	},
	{
	    "id": 1000000018,
	    "name": "Big House",
	    "city": "not important",
	    "address": "not important",
	    "tel": "not important"
	}
]

I would this add this to the Tests tab to loop through the array and grab the id from the object that has Square within the name:

_.each(pm.response.json(), (item) => {
    if(item.name.includes('Square')) {
        pm.environment.set('departmentID', item.id)
    }
}) 

This is only really going the work if you have a single object in the array with Square in the name property if you had more than one occurrence, it’s just going to overwrite the variable and set the last one. You could add something to the variable name as a unique value to stop that from happening.

Thank you for the solution!

1 Like