Find the right object in array and assert on it

Hi there! It will be a noob question and I’m so sorry for it. But I cannot find any way of doing it on my own, so I thought I could use some help.

So, if I have a JSON response and there is some object in the array, how could I assert on it if I don’t know its index?

Let’s say that it’s the response that I want to test:

{
    "users": [
        {
            "name": "Julius",
            "pet": "iguana"
        },
        {
            "name": "Bob",
            "pet": "dog"
        },
        {
            "name": "Dave",
            "pet": "cat"
        }
    ]
}

I need to verify if user ‘Julius’ has an ‘iguana’ pet.

If I would know Julius’s index, then I would check his pet this way:

pm.test("Julius got a pet iguana", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.users[0].pet).to.eql("iguana")
});

But unfortunately, I don’t know what his index is. I guess that I need to do something to find the index of ‘Julius’ record first, so I could assert on him and his pet. How could I do it?

I kept reading about some find methods but I didn’t find any examples that would help me with understanding how to use those.

I’ll be much obliged for any clues!

You could use something like:

let obj = pm.response.json().users.find(e => e.name === 'Julius');
console.log(obj.pet);

You could use that function inside a test and expect against obj.pet to equal iguana.

For example:

pm.test('Name of pet matches', () => {
    let obj = pm.response.json().users.find(e => e.name === 'Julius');
    pm.expect(obj.pet).to.eql('iguana');    
});
3 Likes

That’s it, it solved my issue. Thank you so much, Danny! :slight_smile:

1 Like