Help me to save id of an object having a certain name

Hello,

I have a response like this:

{
	"documents": [
		{
			"id": 1,
			"name": "document1"
		},
		{
			"id": 3,
			"name": "document3"
		},
		{
			"id": 2,
			"name": "document2"
		},
		...
	]
}

The order of objects in “documents” can be different for any new request.
So, I need to do something like:

if “name” = “document3” then set variable “documentId3” = “3”,
if “name” = “document1” then set variable “documentId1” = “1”
and etc. for each document from the response.

Finally I need to see in variables:
documentId1 = id of the document with name “document1”
documentId2 = id of the document with name “document2”
and so on.

How can I do it?

Hey @Leveralex :wave:

Welcome to the Postman Community! :postman:

You could use the JS function .find() to locate those objects and then save the id from the result.

let resp = pm.response.json();
let document1 = resp.documents.find(({ name }) => name === "document1");

pm.environment.set('document1', document1.id);

I’m sure you could replicate that for the other objects to save the values from the response.

@danny-dainton Thank you! It works :slight_smile:

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.