Decypher
Decypher

Reputation: 700

Postman get variable used in array find doesn't work

Using the newest version of Postman.

I have a predefined variable "useridToken" which is a number: 123456

var useridToken = pm.environment.get("useridToken");
//console.log(useridToken);

var jsonData = pm.response.json();
const user = jsonData.find(u => u.user_metadata.employeeId === useridToken);
const userid = user ? user.user_id : 'not found';

pm.environment.set("user_id", userid);

Whenever I run this code, it returns errors.
The console log output is the number as an integer: 123456

Whenever I run the following code:

var useridToken = 123456

var jsonData = pm.response.json();
const user = jsonData.find(u => u.user_metadata.employeeId === useridToken);
const userid = user ? user.user_id : 'not found';

pm.environment.set("user_id", userid);

It works like a charm, but I don't want the hardcoded useridToken in my code, I would like to get it from my environment variables. I don't quite understand why the first part isn't working? What am I overseeing?

Upvotes: 0

Views: 297

Answers (2)

Naveen Kumar V
Naveen Kumar V

Reputation: 2819

SOLUTION:

Since you are using === operator, it checks for the type of the variables too. The type for both operands might be different on certain scenarios. So, use the following to avoid the issue.

const user = jsonData.find(u => +u.user_metadata.employeeId === +useridToken); // converts to number then checks

or

const user = jsonData.find(u => u.user_metadata.employeeId.toString() === useridToken.toString()); // converts to string then checks

or

const user = jsonData.find(u => u.user_metadata.employeeId == useridToken); // checks without the operands type. (not recommended)

Upvotes: 1

Sivcan Singh
Sivcan Singh

Reputation: 1892

This is happening because in your .find method you're using === comparison, and when you fetch from environment you always get it as a 'string' and not a 'number' (Postman always gives the value of the environment variable in the string format)

So when you use a === comparison in JS, it also checks the type of the data, here string === number will actually be false and that's why your find doesn't work.

So, you need to update your code to actually parse the integer that you got from the environment.

This should fix your issue:

var useridToken = parseInt(pm.environment.get("useridToken"));

Upvotes: 2

Related Questions