I`m trying to filter an array but I don t succeed to filter array inside the object
I will give us an example of how the array is:
const data = [
{
path: 'data1',
main: [
{
path: 'mainData11'
},
{
path: 'mainData12'
}
]
},
{
path: 'data2',
main: [
{
path: 'mainData21'
},
{
path: 'mainData22'
}
]
}
];
const filterArray = ['data1', 'mainData12'];
expected result
const data = [
{
path: 'data1'
main: [
{
path: 'mainData12'
}
]
}
]
What I`ve tried
data.filter(el => filterArray.includes(el.path))
I did not succeed to filter the main inside object...
How I do that?
Thanks!
**UPDATE -- CURRENT SOLUTION
data.reduce((results, item) => {
if(filterArray.some(f => item.path === f)){
results.push(
{
...item,
path: item.path,
main: item.main.filter(i => filterArray.some(f => i.path === f))
}
)
};
return results;
}, []);