I have an array of JSON like below
const data = [
{
"uniqueId": 1233,
"serviceTags": [
{
"Id": 11602,
"tagId": "FRRRR",
"missingRequired": [
],
"summaries": [
{
"contract": "ACTIVE",
},
{
"contract": "INACTIVE",
}
],
"lttributes": {
}
}
],
},
{
"uniqueId": 34555,
"serviceTags": [
{
"Id": 11602,
"tagId": "JWJN2",
"missingRequired": [
],
"summaries": [
{
"contract": "ACTIVE",
},
{
"contract": "INACTIVE",
}
],
"lttributes": {
}
}
],
},
{
"uniqueId": 44422,
"serviceTags": [
{
"Id": 11602,
"tagId": "ABC",
"missingRequired": [
],
"summaries": [
{
"contract": "ACTIVE",
},
{
"contract": "INACTIVE",
}
],
"lttributes": {
}
},
{
"Id": 11602,
"tagId": "BBC",
"missingRequired": [
],
"summaries": [
{
"contract": "ACTIVE",
},
{
"contract": "INACTIVE",
}
],
"lttributes": {
}
}
],
}
]
I want to filter array of object by below tagId
const tagId = ['ABC','FRRRR'];
filter array of json should be like
[
{
"uniqueId": 1233,
"serviceTags": [
{
"Id": 11602,
"tagId": "FRRRR",
"missingRequired": [
],
"summaries": [
{
"contract": "ACTIVE",
},
{
"contract": "INACTIVE",
}
],
"lttributes": {
}
}
],
},
{
"uniqueId": 44422,
"serviceTags": [
{
"Id": 11602,
"tagId": "ABC",
"missingRequired": [
],
"summaries": [
{
"contract": "ACTIVE",
},
{
"contract": "INACTIVE",
}
],
"lttributes": {
}
}
],
}
]
try to do by below way but I am not able to get exact output
const r = data.filter(d => d.serviceTags.every(c => tagId.includes(c.tagId)));
console.log(r);
3
Answers
You can use
Array.reduce()
to get the result in the desired form.For each item in the
data
array, we check if any service tags match, using Array.filter().If we get any matches we add the item to the result.
An alternate to the
reduce()
option is tomap()
the data with a nested filter on theserviceTags
and thenfilter()
the result to remove those entries with empty arrays.Before filtering as desired, you would have to map each element to elements that only include the desired
tagId
s as follows: