I recently faced an issue where I had to filter a nested array for a particular property while keeping the outer array intact. Let’s say that we want to filter out the users that have a status of Active
and who also have Basketball
as the item tied to their name from the object of arrays below. Here’s how to go about it:
const data = {
users: [
{
"userId": "123",
"name": "John Smith",
"status": 'inActive',
"items": [
{
"itemId": 1,
"name": "Soccer ball",
}
]
},
{
"userId": "456",
"name": "Steve Johnson",
"status": 'Active',
"items": [
{
"itemId": 2,
"itemName": "Basketball",
}
]
},
{
"userId": "789",
"name": "Leslie Thompson",
"status": 'inactive',
"items": [
{
"itemId": 3,
"itemName": "Football",
}
]
},
{
"userId": "139",
"name": "Jesse Lang",
"status": 'Active',
"items": [
{
"itemId": 45,
"itemName": "Basketball",
}
]
}
]
};
const result =
data.users.filter((x) => x.status === 'Active').map((y) => {
return {
id: y.userId,
name: y.name,
itemName: y.items.filter((z) => z.itemName === 'Basketball')
}
});
console.log(result);
//[{
id: "456",
itemName: [{
itemId: 2,
itemName: "Basketball"
}],
name: "Steve Johnson"
}, {
id: "139",
itemName: [{
itemId: 45,
itemName: "Basketball"
}],
name: "Jesse Lang"
}]
If we look at the result
variable above, We filter the primary array for the status
property and then chain a map
onto the result in order to deal with the nested array. In the return object, we output the properties that we want from the outer array and then use the filter
method on the nested array to get the users that have Basketball
as the item attached to their name.