0

My response code is as follows:

[
    {
        "id": 364,
        "siteName": "FX21 - PortA",
    },
    {
        "id": 364,
        "siteName": "FX21 - PortB",
    },
    {
        "id": 370,
        "siteName": "FX05 - ER",
    },

In postman I am wanting to populate an array variable with all siteName values only where id = 364. So my expected array is to look like [FX21 - PortA, FX21 - PortB]

I've tried the following but this only returns the first siteName value:

var requiredId = pm.response.json().find(function(element){
    if (element.id == "364"){

        return element;
    }
});
Matt
  • 501
  • 1
  • 12
  • 26
  • 1
    [`find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) returns the first match. You wanted to use [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) instead. – 31piy Apr 18 '19 at 06:50
  • Sorry. That's a typo. Fixed now. – Matt Apr 18 '19 at 06:51
  • 2
    Also instead of `if (element.id == "364"){` you should do `if (element.id ===364){` – brk Apr 18 '19 at 06:52

1 Answers1

0
  • Use a combination of Array.filter to filter id having value 364.
  • And Array.map to map it to an array of only siteName values.
  • Along with destructuring assignment to extract the keys of the object:

const response = [
    {
        "id": 364,
        "siteName": "FX21 - PortA",
    },
    {
        "id": 364,
        "siteName": "FX21 - PortB",
    },
    {
        "id": 370,
        "siteName": "FX05 - ER",
    }
]
function getSiteNameById(idFilter){
 return response.filter(({id}) => id === idFilter).map(({siteName}) => siteName);
}
console.log(getSiteNameById(364));

Or Array.reduce to do it in one shot where you can check for the id and then accumulate the element in the final array:

const response = [
        {
            "id": 364,
            "siteName": "FX21 - PortA",
        },
        {
            "id": 364,
            "siteName": "FX21 - PortB",
        },
        {
            "id": 370,
            "siteName": "FX05 - ER",
        }
    ]
function getSiteNameById(idFilter){
 return response.reduce((acc, ele) => {
    return  ele.id === idFilter ? acc.concat(ele.siteName) : acc;
 }, []);
}
console.log(getSiteNameById(364));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44