Could you please assist me on working out how can I filter for a specific property within a deep nested array of objects?
I want to be able to search for entire array (including parent itself and children) where _speciality is ‘can fly’. As such, in the above, I should get 2 values back (fruit1, fruit3).
I have tried to usual JS operations like .filter, .map but unable to work out how this can be achieved.
Here is what my object looks like:
const foo = {
"fruits": [
{
"fruit1": [{
"categories": { "shape": "square", "size": "large"},
"factories": [{ "city": "delhi", "location": "23 new road"}],
"capacity": [{ "weight": "10kg", "_speciality": "can fly"}]
}]
},
{
"fruit2": [{
"categories": { "shape": "round", "size": "small"},
"factories": [{ "city": "bombay", "location": "13 new road"}],
"capacity": [{ "weight": "14kg", "_speciality": "can sing"}]
}]
},
{
"fruit3": [{
"categories": { "shape": "rectangle", "size": "medium"},
"factories": [{ "city": "bombay", "location": "13 new road"}],
"capacity": [{ "weight": "14kg", "_speciality": "can fly"}]
}]
}
]
}
2
Answers
You will need to tailor your filter to your data. There is no one-size-fits-all approach to this.
Your filter is going to look something like this:
In the snippet below, I introduced some intermediary variables to explain the process in more detail.
The results should be:
Here is one of the many solutions you are looking for
You can easily process the
result
to get the output as required. I am leaving that exercise for you but feel free to get back.Happy Coding!!