Find if a value is in an object inside arrary

Hi there, I’m trying to find an effective way to find if an id is returned in an array of objects.

My JSON response is below. I’m trying to write a test that would be true if one of the objects has a venueId of 8b0c9a4c-3ec9-4cf5-bb9c-ce7441ec895d

Any help on this would be great. I’m trying to avoid looping through the array, as it won’t be efficient later when the array gets larger.

{
    "items": [
        {
            "createdAt": "2020-12-10T15:27:27.660Z",
            "name": "my studio",
            "userId": "auth0|5fd0c3ffe3b04b0076a17769",
            "venueId": "0693ca98-82cb-41c2-9db7-12750066edb8"
        },
        {
            "createdAt": "2020-12-10T15:26:58.987Z",
            "name": "my studio",
            "userId": "auth0|5fd0c3ffe3b04b0076a17769",
            "venueId": "3f8ddde1-fc61-4b00-b608-86a67ff52e9a"
        },
        {
            "createdAt": "2020-12-10T15:28:05.984Z",
            "name": "my studio",
            "userId": "auth0|5fd0c3ffe3b04b0076a17769",
            "venueId": "46ac6b2c-64d4-4b90-ac1a-bc626b0c962c"
        },
        {
            "createdAt": "2020-12-10T15:36:05.076Z",
            "name": "my studio",
            "userId": "auth0|5fd0c3ffe3b04b0076a17769",
            "venueId": "8b0c9a4c-3ec9-4cf5-bb9c-ce7441ec895d"
        },
        {
            "createdAt": "2020-12-10T15:30:45.372Z",
            "name": "my studio",
            "userId": "auth0|5fd0c3ffe3b04b0076a17769",
            "venueId": "94376601-ed78-4355-a294-034109a5a62a"
        },
        {
            "createdAt": "2020-12-10T15:25:45.353Z",
            "name": "my studio",
            "userId": "auth0|5fd0c3ffe3b04b0076a17769",
            "venueId": "aaa3e4cb-9891-42c9-a2a5-cbfa8392d2bc"
        },
        {
            "createdAt": "2020-12-10T15:25:16.106Z",
            "name": "my studio",
            "userId": "auth0|5fd0c3ffe3b04b0076a17769",
            "venueId": "ddb6d540-79f3-483b-bf44-6df8d715ee23"
        }
    ]
}

@simonotter Warm welcome to the community :clap:

Yes so I understand correctly, you just need to check the expected VenueID to be present in any of the element inside the array. May be you can use find() method.

Please try the below snippet. And I believe what you have given above is the a complete JSON.

var resp = JSON.parse(responseBody);
var _ = require('lodash')
//console.log(resp);

var venueExists = _.find(resp.items, function(o) { 
       return o.venueId == "8b0c9a4c-3ec9-4cf5-bb9c-ce7441ec895d"; });
console.log(venueExists);

pm.test("Expected Venue ID is present", function () 
{
    pm.expect((venueExists) != null).to.be.true;
});

Hope it works. Please let me know if you are facing any issues/if this doesn’t fulfill your need :slight_smile:

Thanks, @bpricilla, that’s really helpful. :slightly_smiling_face:

1 Like