Postman get value from JSON where equals a value in array using javascript

  • A+
Category:Languages

Currently using the latest version of Postman: 6.7.4 (Latest)

I'm trying to get a value out of a JSON response body and store it in an environment variable BUT the value 'username' should be equal to my preferred username.

Normally I would extract a value like this:

var jsonData = pm.response.json(); pm.environment.set("useridToken", jsonData.Customers[0].userid); 

This would give me the first item in the list but I do not wish to obtain the first nor the second item from the list. I wish to obtain the userid where username EQUAL "Billy" for example.

Output of the body response:

{ "Customers": [     {         "id": 24,         "userid": 73063,         "username": "BOB",         "firstname": "BOB",         "lastname": "LASTNAME     },     {         "id": 25,         "userid": 73139,         "username": "Billy",         "firstname": "Billy",         "lastname": "lasty"     }    ] } 

Any tips?

I remember in SoapUI it was like this:

$.channels[?(@.is_archived=='false')].id[0] 

I guess it's not possible to do this in JS in Postman?

 


You can use: Array.prototype.find():

const data = {   "Customers": [{       "id": 24,       "userid": 73063,       "username": "BOB",       "firstname": "BOB",       "lastname": "LASTNAME"     },     {       "id": 25,       "userid": 73139,       "username": "Billy",       "firstname": "Billy",       "lastname": "lasty"     }   ] };  const user = data.Customers.find(u => u.username === 'Billy'); const userid = user ? user.userid : 'not found';  console.log(user); console.log(userid);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: