Postman: Use the request name within the declaration of an environment variable

Viewed 1456

I would like to use Postman to set an Environment variable in a dynamic way and use the dataObject..attribute2's values based on the request name. This script is used within the Pre-req section.

Situation: I have a json data object:

var dataObject = {

    "request01": {
        "attribute1": 123456789,
        "attribute2": "asdfghjkl"
    },
    "request02": {
        "attribute1": 987654321,
        "attribute2": "lkjhgfdsa"
    }
}

And I have these 2 requests in the same folder with the names:

  • request01
  • request02

Now, I want to define the value of this allocation, so I assign the attribute2 value to the variable dynamicAttribute2. If I do this in a static way it is like this:

postman.setEnvironmentVariable("dynamicAttribute2", dataObject.request02.attribute2);

Now this question how to do it properly in a dynamic way, depending on the request name, each. I tried to do this:

postman.setEnvironmentVariable("dynamicAttribute2", dataObject.{request.info.name}.attribute2);

The issue is that Postman cannot resolve the object reference to the attribute.

Question

What's the correct way to use this?

2 Answers

You can dynamically access an object's key (to retrieve the property or set it) using square brackets, similar to arrays. This should work:

postman.setEnvironmentVariable(
  "dynamicAttribute2",
  dataObject[request.info.name].attribute2
);
Related