I get a JSON data source that looks like this:
[
{
"id": 1,
"name": 'name',
"array": [
{ "id": 1}, { "id": 2}
]
},
{...}
]
I’d like to filter this data according to the id contained in the array
.
But I don’t know how to do this with array.filter and includes. Can you help me?
2
Answers
You can achieve filtering of the above with the following:
filter
is used to go through each item in thedata
array. For each item, thesome
method is used to check if there is any object in thearray
field that has anid
equal toidToFind
. If there is, the item is included in thefilteredData
array.Edit:
If you want to filter based on multiple ids, you can change the code to:
It’s very easy to use filter() for your use-case. You just pass an arrow function, whose parameter is named
item
in this case and which returns(item.id === 1)
(or whatever criteria you want to use).