'Filtering values from a json get response

I am relatively new in Postman and I am having troubles filtering my response. I tried various methods but either I am going the wrong way or I am doing it wrong.

[
     {
         "id": "62f9-4fe5-82c4-4ecf",
         "description": "BLUE",
         "original_name": "AZURE_BLUE"
     },
     {
         "id": "98cd-95ed-45e9-a855",
         "description": "GREEN",
         "original_name": "LEAF_GREEN"
     }
   ]

What I am trying to do is to get the id value of Azure_Blue and pass it in a global variable to later use it on a different API call but I am stuck.

I tried

const obj = JSON.parse(responseBody)
if(obj.original_name ==='AZURE_BLUE'){
    var subj=obj.id;
    postman.setGlobalVariable("id", subj);
}

and

pm.test("Get id", function () {
if(pm.response.code === 200){
    var obj = JSON.parse(responseBody);
    _.each(pm.response.json().data,(item) =>{
        if(item.original_name === 'AZURE_BLUE'){
            var subj=obj.id;
            postman.setGlobalVariable("id", subj);
        }
    })
}
});

Any help is greatly appreciated



Solution 1:[1]

This would work

const res = JSON.parse(responseBody)
const obj = res.find(({original_name}) => original_name === 'AZURE_BLUE');
pm.globals.set('id', obj.id);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lucas-nguyen-17