Retrieve Value from array where another value is not null or undefined

Hi
My response body looks like:

[
{
“assetId”: 100000005,
“name”: “CROW HUT”,
“status”: “OPEN”,
“region”: null,
“x”: 1555519,
“y”: 5428621
},
{
“assetId”: 100001473,
“name”: “Manson-Nicholls Memorial Hut”,
“status”: “OPEN”,
“region”: null,
“x”: 1541459,
“y”: 5316142
},
{
“assetId”: 100001528,
“name”: “Ada Pass Hut”,
“status”: “OPEN”,
“region”: null,
“x”: 1555272,
“y”: 5316286
},
{
“assetId”: 100001561,
“name”: “Lake Christabel Hut”,
“status”: “OPEN”,
“region”: 4567,
“x”: 1538742,
“y”: 5301420
},
{
“assetId”: 100001589,
“name”: “Croesus Top Hut”,
“status”: “OPEN”,
“region”: null,
“x”: 1467429,
“y”: 5316392
},
{
“assetId”: 100001595,
“name”: “Mudflats Hut”,
“status”: “OPEN”,
“region”: 1234,
“x”: 1466730,
“y”: 5251773
}
]

Some of the data in the array has region as null

I want to retrieve asset ids of the data where region is not null
maybe assign that to another array

Can someone please help.

Thanks

Hey @Xinfinity,
You can simply run the following in your test script to filter out all the objects from the array with region as null:

// Replace the responseArray with your response array that you want to filter
let filteredArray = responseArray.filter((r) => r.region === null);

console.log(filteredArray); // This contains the filtered array

Read about filter here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Now incase you want the assetId’s then you can do the following

// This will print the ids to the console
filteredArray.map((r) => console.log(r.assetId)); 


//  Incase you want to store those id's in a separate array you 
// can do the following
let assetIdsWithRegionNull = filteredArray.map((r) => r.assetId); 

console.log(assetIdsWithRegionNull);

Just in case you’re interested in a one liner then here you go:
Using pre-built in lodash

let assetIds = _.chain(responseArray).filter({ region: null }).map((r) => r.assetId).value();

Hope this helps :slight_smile:

thx that helped :slight_smile:

1 Like