Search code examples
javascriptpostmanpostman-testcase

Find Postman sub-object based on property


I'd like to get the first item which has "shipping":"ABC" in the response below. In this case, the expected response should be 37

I'm not very good at writing Javascript test in Postman.

Thank you.

{
    "37": {
        "shipping_id": 37,
        "position": 0,
        "status": "D",
        "shipping": "ABC",
        "delivery_time": "24h-72h"
    },
    "36": {
        "shipping_id": 36,
        "position": 0,
        "status": "D",
        "shipping": "DEF",
        "delivery_time": ""
    },
    "28": {
        "shipping_id": 28,
        "position": 0,
        "status": "D",
        "shipping": "GHI",
        "delivery_time": ""
    }

Solution

  • I found the solution from another post :

    var response = JSON.parse(responseBody);
    
    const result = Object.keys(response).find(v => response[v].shipping === 'ABC');
    
    //your object keys are equal to id, you can just return key
    console.log(result);
    
    // if your object keys can be different from id you can do this
    console.log(response[result].shipping_id);