I recently ran into an issue where I needed to filter out some items in a nested array inside an object of arrays in Javascript. After trial and error, I found out how to extract the information that I needed.
Suppose we have an object of arrays which has users and the sporting equipment that they have borrowed. Here is our data object:
const data = {
users: [
{
"id": "123",
"name": "John Smith",
"items": [
{
"id": 1,
"name": "Soccer ball",
}
]
},
{
"id": "456",
"name": "Steve Johnson",
"items": [
{
"id": 2,
"name": "Basketball",
}
]
},
{
"id": "789",
"name": "Leslie Thompson",
"items": [
{
"id": 3,
"name": "Football",
}
]
}
]
};
Let’s say we want to find out who borrowed the basketball. We first start by using the filter
function in order to filter out the data that we want:
const output = data.users.filter(x => x.items.every(y => y.name.includes("Basketball")));
We use two functions in addition to filter
. First, we use the every
function. The every
function is used to test whether the parameters that you pass inside it exist. It returns a boolean. The includes
function searches inside an array to see whether the value that you are looking for exists.
If we console.log(output)
we get the following:
(1) [Object]
0: Object
id: "456"
name: "Steve Johnson"
items: Array(1)
0: Object
id: 2
name: "Basketball"