I have a 3-layer array that I want to filter out data based on the child array values. I can get semi-correct results but the last part I am having issues with.
{
"id": 1,
"grandparent": "Timmy",
"parents": [
{
"id": 1,
"parent": "Johnny",
"children": [
{
"id": 1,
"child": "Sam",
"checked": true
},
{
"id": 1,
"child": "Ted",
"checked": false
}
]
},
{
"id": 2,
"parent": "Jessica",
"children": [
{
"id": 1,
"child": "Sam",
"checked": false
}
]
},
]
}
I have this so far:
grandparents.value = value.value.map((el) => ({
...el,
parents: el.components.filter((parent) => parent.children?.some((child) => child.checked))
}))
and it returns this result:
{
"id": 1,
"grandparent": "Timmy",
"parents": [
{
"id": 1,
"parent": "Johnny",
"children": [
{
"id": 1,
"child": "Sam",
"checked": true
},
{
"id": 1,
"child": "Ted",
"checked": false
}
]
}
]
}
So the parents array is working. However, I also need the children array to also filter out if they are not checked.
Expected results
{
"id": 1,
"grandparent": "Timmy",
"parents": [
{
"id": 1,
"parent": "Johnny",
"children": [
{
"id": 1,
"child": "Sam",
"checked": true
}
]
}
]
2
Answers
filter()
will only add or remove the object, not alter the innerchildren
array.You could adopt a
reduce()
option where youfilter
the childrenif
we got a child, add this object with the updatedchildren
arraymap
over theparents
array, for each parent, we filter thechildren
array to keep only the checked ones, after that usefilter()
again to remove parents whose children array is empty after filtering.