I have a json like this and I want to get all the areas that have almost one service that has the selected property equal to true.
{
"areas": [
{
"name": "area 1",
"services": [
{
"label": "srv 1",
"selected": true
},
{
"label": "srv 2",
"selected": false
},
{
"label": "srv 3",
"selected": false
},
{
"label": "srv 4",
"selected": true
}
]
},
{
"name": "area 2",
"services": [
{
"label": "srv 1",
"selected": false
},
{
"label": "srv 2",
"selected": true
},
{
"label": "srv 3",
"selected": false
},
{
"label": "srv 4",
"selected": false
}
]
},
{
"name": "area 3",
"services": [
{
"label": "srv 1",
"selected": false
},
{
"label": "srv 2",
"selected": false
},
{
"label": "srv 3",
"selected": false
}
]
},
{
"name": "area 4",
"services": [
{
"label": "srv 1",
"selected": true
},
{
"label": "srv 2",
"selected": false
},
{
"label": "srv 3",
"selected": true
}
]
}
]
}
The result must contains only the areas with only the services with the selected property equal to true and must be pointed out without mutating the original array.
With this code
const result = areas.filter(area =>
services.some(srv => srv.selected == true)
);
I obtain all the areas, but inside these areas I have all the services (with selected true and with selected false).
This is what I want instead:
{
"areas": [
{
"name": "area 1",
"services": [
{
"label": "srv 1",
"selected": true
},
{
"label": "srv 4",
"selected": true
}
]
},
{
"name": "area 2",
"services": [
{
"label": "srv 2",
"selected": true
}
]
},
{
"name": "area 4",
"services": [
{
"label": "srv 1",
"selected": true
},
{
"label": "srv 3",
"selected": true
}
]
}
]
}
Thanks