API Testing 'A Beginners View': JavaScript - Array.prototype.find() and Array.prototype.findIndex()

API Testing ‘A Beginners View’: JavaScript - Array.prototype.find() and Array.prototype.findIndex()

Array.prototype.find()

The find() method returns the value of the first value of the array to be tested which passes the condition specified. It checks all the values in the array and whichever value satisfies the condition first would be picked and displayed in the output. If the value is not found it returns undefined.

Let’s check out some examples to understand it better;

Example1: Using Arrow Function

Response Body:

{
   "args":{
      
   },
   "data":{
      "FirstName":[
         {
            "value":"{{RandomFirstName}}"
         }
      ],
      "Specialty":[
         {
            "name":"NEUROLOGY",
            "experience":"2"
         },
         {
            "name":"Dermatology",
            "experience":"2"
         },
         {
            "name":"Ortho",
            "experience":"2"
         }
      ]
   },
   "files":{
      
   },
   "form":{
      
   },
   "headers":{
      "x-forwarded-proto":"https",
      "x-forwarded-port":"443",
      "host":"postman-echo.com",
      "x-amzn-trace-id":"Root=1-5fd86d42-7d196eb86048629c2b3ea2ca",
      "content-length":"288",
      "content-type":"application/json",
      "user-agent":"PostmanRuntime/7.26.8",
      "accept":"*/*",
      "cache-control":"no-cache",
      "postman-token":"065034d3-4e05-4d1b-872d-382f2579524d",
      "accept-encoding":"gzip, deflate, br",
      "cookie":"sails.sid=s%3A6n5cRYOmPZd0CgxhkfCCHO6rFlTzSFfw.9ZTgkbZcBTzwWSiBLXKE%2BktjLAb6IdSuIMFNxLxnK9Y"
   },
   "json":{
      "FirstName":[
         {
            "value":"{{RandomFirstName}}"
         }
      ],
      "Specialty":[
         {
            "name":"NEUROLOGY",
            "experience":"2"
         },
         {
            "name":"Dermatology",
            "experience":"2"
         },
         {
            "name":"Ortho",
            "experience":"2"
         }
      ]
   },
   "url":"https://postman-echo.com/post"
}

Test Script:

//Using function how to find an object in array by 'find' method

var resp = JSON.parse(responseBody);

function find_result1(value) {
    return value.name === 'Dermatology';

}

console.log(array_value.find(find_result1));

Console Output:

Example 2: Using function how to find an object in array by ‘find’ method

Test Script:

var resp = JSON.parse(responseBody);
console.log(resp);
const array_value = resp.data.Specialty;
console.log(array_value);

//Using arrow function how to find an object in array by 'find' method

const result = array_value.find( ({ name }) => name === 'NEUROLOGY' );

console.log(result);

Console Output:

The explanation for the above examples:

The above example is based on an array that has three values to it as below:

I have used the ‘find’ method in two different ways to identify the object that satisfies the conditions:

  • name === ‘NEUROLOGY’
  • name === ‘Dermatology’

After execution, the output returns the value which satisfied the condition.

Array.prototype.findIndex()

In continuation of the above feature, if we need to know the index of the element that we found, this can be done by the findIndex() method. It returns the index of the first element in the array that satisfies the condition we provide. If no element passes the test condition, it returns -1.

Example: In continuation to the above snippet when we add the below code, index will be returned

//How to find the index of the result
//Using function how to find an object in array by 'find' method

function find_result1(value) {
    return value.name === 'Dermatology';
}

console.log(array_value.find(find_result1));

console.log(array_value.findIndex(find_result1)); //this is using function

Console Output:

Hope this was useful :innocent:
Happy Learning :innocent:

2 Likes

hi There,

Very useful one, similar issue – Would pls fix this issue –
need to verify the property name - “sipaddress” : “+a682@com.com
issue – there are ‘N’ number of property name by sipaddress with different values
here is the response body –

{

"message": "All SIP addresses fetched successfully.",

"data": [

    {

        "tenant": "Pit",

        "location": "LOC761",

        "provider": "TTEC22",

        "sipaddress": "23632224022021",

        "inUse": false,

        "updatedAt": 1614200241078

    },

    {

        "tenant": "Pit",

        "location": "LOC771",

        "sipaddress": "+5734353@qa22.org",

        "updatedAt": 1614200222359,

        "createdAt": 1614118371824,

        "provider": "TTEC22",

        "objectGUID": "3b96d6e5-681d-44cb-9144-6fc5b0702300",

        "inUse": false

    },

    {

        "tenant": "Pit",

        "location": "MA",

        "sipaddress": "+7434452@qa13.org",

        "updatedAt": 1614118369411,

        "createdAt": 1614118369411,

        "provider": "TTEC13",

        "objectGUID": "62046239-c6aa-453a-8953-d500ce270e3c",

        "inUse": false

    },

    {

        "tenant": "Pit",

        "location": "MA",

        "sipaddress": "+6221418@qa32.org",

        "updatedAt": 1614118374484,

        "createdAt": 1614118374484,

        "provider": "TTEC32",

        "objectGUID": "88ac5f0a-926d-47a5-a7c6-d4d0d2612e96",

        "inUse": false

    },

    {

        "tenant": "Axecap",

        "location": "IN",

        "sipaddress": "+9053@six.com",

        "updatedAt": 1614697684203,

        "createdAt": 1614697684203,

        "provider": "AWS",

        "objectGUID": "253cb226-6fa1-47bc-8010-143f1d11e6ec",

        "inUse": true

    },

    {

        "tenant": "Pit",

        "location": "LOC814",

        "sipaddress": "63634524022021",

        "updatedAt": 1614200473775,

        "createdAt": 1614200473775,

        "provider": "TTEC22",

        "objectGUID": "5e357fdf-449f-4515-b943-45979818cbf1",

        "inUse": false

    },

    {

        "tenant": "Axecap",

        "location": "US",

        "sipaddress": "+1111@abc.com",

        "updatedAt": 1614693991996,

        "createdAt": 1614286862404,

        "provider": "AWS",

        "objectGUID": "cf9968cc-31f0-470e-9c35-48218f7cac8e",

        "inUse": false

    },

    {

        "tenant": "Pit",

        "location": "MA",

        "sipaddress": "+4974113@qa26.org",

        "updatedAt": 1614118372951,

        "createdAt": 1614118372951,

        "provider": "TTEC26",

        "objectGUID": "60641345-285a-4fe5-9acd-5b9a6031fb00",

        "inUse": false

    },

    {

        "tenant": "Axecap",

        "location": "IN",

        "sipaddress": "+y559@org.com",

        "updatedAt": 1614711139290,

        "createdAt": 1614711139290,

        "provider": "AWS",

        "objectGUID": "fe08d4a0-9777-46b4-b964-ca50f18ba085",

        "inUse": true

    },

    {

        "tenant": "Axecap",

        "location": "IN",

        "sipaddress": "+h98@net",

        "updatedAt": 1614710904665,

        "createdAt": 1614710904665,

        "provider": "AWS",

        "objectGUID": "b4633ea6-4ab5-467a-8c90-60385f1910eb",

        "inUse": true

    },

    {

        "tenant": "Pit",

        "location": "LOC667",

        "sipaddress": "15662324022021",

        "updatedAt": 1614200496183,

        "createdAt": 1614200496183,

        "provider": "TTEC22",

        "objectGUID": "07ad2444-6b5d-4934-ae95-2829732838b4",

        "inUse": false

    },

],

"total": 243

goes upto 200 + data…

Hi @poornapragnaps thanks for connecting!

{
    "args": {},
    "data": {
        "data": [
            {
                "tenant": "Pit",
                "location": "LOC761",
                "provider": "TTEC22",
                "sipaddress": "23632224022021",
                "inUse": false,
                "updatedAt": 1614200241078
            },
            {
                "tenant": "Pit",
                "location": "LOC771",
                "sipaddress": "+5734353@qa22.org",
                "updatedAt": 1614200222359,
                "createdAt": 1614118371824,
                "provider": "TTEC22",
                "objectGUID": "3b96d6e5-681d-44cb-9144-6fc5b0702300",
                "inUse": false
            },
            {
                "tenant": "Pit",
                "location": "MA",
                "sipaddress": "+7434452@qa13.org",
                "updatedAt": 1614118369411,
                "createdAt": 1614118369411,
                "provider": "TTEC13",
                "objectGUID": "62046239-c6aa-453a-8953-d500ce270e3c",
                "inUse": false
            },
            {
                "tenant": "Pit",
                "location": "MA",
                "sipaddress": "+6221418@qa32.org",
                "updatedAt": 1614118374484,
                "createdAt": 1614118374484,
                "provider": "TTEC32",
                "objectGUID": "88ac5f0a-926d-47a5-a7c6-d4d0d2612e96",
                "inUse": false
            },
            {
                "tenant": "Axecap",
                "location": "IN",
                "sipaddress": "+9053@six.com",
                "updatedAt": 1614697684203,
                "createdAt": 1614697684203,
                "provider": "AWS",
                "objectGUID": "253cb226-6fa1-47bc-8010-143f1d11e6ec",
                "inUse": true
            },
            {
                "tenant": "Pit",
                "location": "LOC814",
                "sipaddress": "63634524022021",
                "updatedAt": 1614200473775,
                "createdAt": 1614200473775,
                "provider": "TTEC22",
                "objectGUID": "5e357fdf-449f-4515-b943-45979818cbf1",
                "inUse": false
            },
            {
                "tenant": "Axecap",
                "location": "US",
                "sipaddress": "+1111@abc.com",
                "updatedAt": 1614693991996,
                "createdAt": 1614286862404,
                "provider": "AWS",
                "objectGUID": "cf9968cc-31f0-470e-9c35-48218f7cac8e",
                "inUse": false
            },
            {
                "tenant": "Pit",
                "location": "MA",
                "sipaddress": "+4974113@qa26.org",
                "updatedAt": 1614118372951,
                "createdAt": 1614118372951,
                "provider": "TTEC26",
                "objectGUID": "60641345-285a-4fe5-9acd-5b9a6031fb00",
                "inUse": false
            },
            {
                "tenant": "Axecap",
                "location": "IN",
                "sipaddress": "+y559@org.com",
                "updatedAt": 1614711139290,
                "createdAt": 1614711139290,
                "provider": "AWS",
                "objectGUID": "fe08d4a0-9777-46b4-b964-ca50f18ba085",
                "inUse": true
            },
            {
                "tenant": "Axecap",
                "location": "IN",
                "sipaddress": "+h98@net",
                "updatedAt": 1614710904665,
                "createdAt": 1614710904665,
                "provider": "AWS",
                "objectGUID": "b4633ea6-4ab5-467a-8c90-60385f1910eb",
                "inUse": true
            },
            {
                "tenant": "Pit",
                "location": "LOC667",
                "sipaddress": "15662324022021",
                "updatedAt": 1614200496183,
                "createdAt": 1614200496183,
                "provider": "TTEC22",
                "objectGUID": "07ad2444-6b5d-4934-ae95-2829732838b4",
                "inUse": false
            }
        ]
    },
    "files": {},
    "form": {},
    "headers": {
        "x-forwarded-proto": "https",
        "x-forwarded-port": "443",
        "host": "postman-echo.com",
        "x-amzn-trace-id": "Root=1-6042b718-5275b4d5665aa0b25e8cba78",
        "content-length": "2982",
        "authorization": "Basic N2ZhZTNjYzg1YTQzNDNkYWFhN2E4YWQzYTk3NWM3OTQ6M0VjOTZFMzljNDEwNEExM0FGOEExNUNDYjZjNzU2RDU=",
        "content-type": "application/json",
        "user-agent": "PostmanRuntime/7.26.10",
        "accept": "*/*",
        "cache-control": "no-cache",
        "postman-token": "eb1c4f38-812e-40a3-8a97-aeec0405eee8",
        "accept-encoding": "gzip, deflate, br"
    },
    "json": {
        "data": [
            {
                "tenant": "Pit",
                "location": "LOC761",
                "provider": "TTEC22",
                "sipaddress": "23632224022021",
                "inUse": false,
                "updatedAt": 1614200241078
            },
            {
                "tenant": "Pit",
                "location": "LOC771",
                "sipaddress": "+5734353@qa22.org",
                "updatedAt": 1614200222359,
                "createdAt": 1614118371824,
                "provider": "TTEC22",
                "objectGUID": "3b96d6e5-681d-44cb-9144-6fc5b0702300",
                "inUse": false
            },
            {
                "tenant": "Pit",
                "location": "MA",
                "sipaddress": "+7434452@qa13.org",
                "updatedAt": 1614118369411,
                "createdAt": 1614118369411,
                "provider": "TTEC13",
                "objectGUID": "62046239-c6aa-453a-8953-d500ce270e3c",
                "inUse": false
            },
            {
                "tenant": "Pit",
                "location": "MA",
                "sipaddress": "+6221418@qa32.org",
                "updatedAt": 1614118374484,
                "createdAt": 1614118374484,
                "provider": "TTEC32",
                "objectGUID": "88ac5f0a-926d-47a5-a7c6-d4d0d2612e96",
                "inUse": false
            },
            {
                "tenant": "Axecap",
                "location": "IN",
                "sipaddress": "+9053@six.com",
                "updatedAt": 1614697684203,
                "createdAt": 1614697684203,
                "provider": "AWS",
                "objectGUID": "253cb226-6fa1-47bc-8010-143f1d11e6ec",
                "inUse": true
            },
            {
                "tenant": "Pit",
                "location": "LOC814",
                "sipaddress": "63634524022021",
                "updatedAt": 1614200473775,
                "createdAt": 1614200473775,
                "provider": "TTEC22",
                "objectGUID": "5e357fdf-449f-4515-b943-45979818cbf1",
                "inUse": false
            },
            {
                "tenant": "Axecap",
                "location": "US",
                "sipaddress": "+1111@abc.com",
                "updatedAt": 1614693991996,
                "createdAt": 1614286862404,
                "provider": "AWS",
                "objectGUID": "cf9968cc-31f0-470e-9c35-48218f7cac8e",
                "inUse": false
            },
            {
                "tenant": "Pit",
                "location": "MA",
                "sipaddress": "+4974113@qa26.org",
                "updatedAt": 1614118372951,
                "createdAt": 1614118372951,
                "provider": "TTEC26",
                "objectGUID": "60641345-285a-4fe5-9acd-5b9a6031fb00",
                "inUse": false
            },
            {
                "tenant": "Axecap",
                "location": "IN",
                "sipaddress": "+y559@org.com",
                "updatedAt": 1614711139290,
                "createdAt": 1614711139290,
                "provider": "AWS",
                "objectGUID": "fe08d4a0-9777-46b4-b964-ca50f18ba085",
                "inUse": true
            },
            {
                "tenant": "Axecap",
                "location": "IN",
                "sipaddress": "+h98@net",
                "updatedAt": 1614710904665,
                "createdAt": 1614710904665,
                "provider": "AWS",
                "objectGUID": "b4633ea6-4ab5-467a-8c90-60385f1910eb",
                "inUse": true
            },
            {
                "tenant": "Pit",
                "location": "LOC667",
                "sipaddress": "15662324022021",
                "updatedAt": 1614200496183,
                "createdAt": 1614200496183,
                "provider": "TTEC22",
                "objectGUID": "07ad2444-6b5d-4934-ae95-2829732838b4",
                "inUse": false
            }
        ]
    },
    "url": "https://postman-echo.com/post"
}

Hey @poornapragnaps I have tried to replicate the body you shared on postman echo post request and asserted based on the above response as follow:

var resp = JSON.parse(responseBody);

console.log(resp);

console.log(resp.data);

for (var i = 0;i<resp.data.data.length;i++)

{

if ((resp.data.data[i].sipaddress) == “+9053@six.com”)

{

pm.test("Property Name - “sipaddress” Check", true);

console.log("Property Name - “sipaddress” : " + resp.data.data[i].sipaddress);

}

}

You can refer this and change the snippet as per your need, you need to tweak in with this won’t be a direct solution here.
Hope this solves your problem. If anything more or not clear please feel free to comment, happy to help you :slight_smile:

@jency.stella19 , Sorry it’s not working!

could you pls help to share the error you are getting.

@jency.stella19 , Hi here it is – There was an error in evaluating the test script: SyntaxError: Invalid or unexpected token

You could also do the same using lodash to loop through the data:

_.each(pm.response.json().data, (obj) => {
        if ((obj.sipaddress) === "+9053@six.com") {
            console.log("Property Name - “sipaddress” : " + obj.sipaddress);
    }
})

Or log the object that contains that sipaddress

let obj = pm.response.json().data.find(a => a.sipaddress === '+9053@six.com');

console.log(obj);

2 Likes

I think that data have been repeated twice in the script

1 Like
jsonData = pm.response.json()

pm.test("Verify value", function () {

    pm.expect(jsonData['data'].find((a) => a['sipaddress'] === "+9053@six.com")['sipaddress']).to.equal("+9053@six.com")

});

you can use array.find , it finds the object that has the sipaddress and then explicitly take that value and validate

2 Likes

Hi @danny-dainton the response shared was incorrect by me my bad sorry for that hence the issue, I have now pasted the correct response to be asserted.

Hi @poornapragnaps I have edited my reply post above pls help to check once again with the solution shared in this forum, won’t be a direct solution you need to modify snippet as per your need. If anything more feel free to connect.

1 Like