Filter function with postman response

I am using Postman to capture some attributes from a response.
Response is as below:

{
    "data": [
        {
            "id": "ws-abc",
            "type": "workspaces",
            "attributes": {
                "environment": "default",
                "locked": false,
                "name": "Practice"
            }
        },
        {
			"id": "ws-xyz",
            "type": "workspaces",
            "attributes": {
                "environment": "default",
                "locked": false,
            }   "name": "Practice-1"
        },
		{
			"id": "ws-xyz",
            "type": "workspaces",
            "attributes": {
                "environment": "default",
                "locked": false,
                "name": "Practice-2"
			}
	    }
	]
}

I want to extract id (line #4) for the workspace named Practice (line #9).

I am able to do that using below code, but I also want to use the name filtering.

const response = pm.response.json();
console.log(response.data[1].id)

When I include the below variable, I am getting an error:

const workspaceName = response.filter((ws) => ws.data.attributes.name === "Practice");
TypeError: response.filter is not a function

I understand the filter function can only be used with arrays, and my response is not an array.

How to I achieve this ? I am new to Postman and JavaScript and appreciate your help!

1 Like

Hey @jijo333

It looks like you would need to do something like this to filter the data array:

const workspaceName = response.data.filter(ws => ws.attributes.name === "Practice");
4 Likes

Thank you @danny-dainton , that solved the problem!

2 Likes

Hi

const workspaceName = JSON.stringify(response.response.filter(ws => ws.errorCode === "00000"));

this is my response

{
	"response": [{
		"errorCode": "00000",
		"message": "SUCCESS"
	}]

do i need to covert to string always ? as I have done here

Where’s the rest of the script code that’s capturing the response body? Why are using stringify? What are you doing with workspaceName after this?

It should be something like this:

const workspaceName = pm.response.json().response.filter(ws => ws.errorCode === "00000");

Thnaks @danny-dainton