I have an array of objects. Every object has hasPermission
property and children
property.
children property is also an array of objects and every object has hasPermission
property.
My array like this:
const navigationMenus = [
{
hasPermission: false,
name: 'Main',
type: 'section',
children: [
{
hasPermission: true,
name: 'Test',
type: 'item',
link: '/test'
}
]
},
{
hasPermission: true,
name: 'Master',
type: 'section',
children: [
{
hasPermission: true,
name: 'Operator Group',
type: 'item',
link: '/operator-group'
},
{
hasPermission: false,
name: 'Operation Group',
type: 'item',
link: '/operation-group'
}
]
}
];
Based on hasPermission
property I want another array which holds only those objects which hasPermission
property is true.
I tried with this approach.
const permittedNavigationMenus = []
for (let i = 0; i < navigationMenus.length; i++) {
const section = navigationMenus[i];
if (section.hasPermission) {
const permittedSection = {
name: section.name,
type: section.type,
children: []
}
for (let j = 0; j < section.children.length; j++) {
const item = section.children[j]
if (item.hasPermission) {
permittedSection.children.push(item)
}
}
permittedNavigationMenus.push(permittedSection)
}
}
console.log(JSON.stringify(permittedNavigationMenus, null, 2))
Is there any better solution?