I have got two arrays . I am filtering based groupKey with PubSidebar.
You could take a filtering for any depth and reassemble the objects for the result.
const
filter = ({ content = [], ...o }) => {
content = content.flatMap(filter);
if (o.role !== 'public' && !groupKey.includes(o.value)) return [];
return content.length ? { ...o, content } : o;
},
groupKey = ['oaDeal', 'Journals', 'Deposit'],
pubSidebar = [{ value: 'Dashboard', role: 'public' }, { value: 'oaDeal', role: 'private', content: [{ role: 'private', value: 'oaDeal' }] }, { value: 'Journals', role: 'public', content: [{ role: 'private', value: 'Journals' }, { role: 'private', value: 'Token' }, { role: 'private', value: 'policy' }, { role: 'private', value: 'Deposit' }, { role: 'public', value: 'test' }] }],
result = pubSidebar.flatMap(filter);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }