Home > Software engineering >  Filter recursive array
Filter recursive array

Time:05-18

I am trying to find the best way (minimal code) to filter a recursive list of items based on some condition. The list describes some navigation that contains multiple sections and each section contains navigation items (where each navigation item can contain a recursive amount of navigation items).

Example:

const navSections = [{
    title: 'Section A',
    items: [
        {
            title: 'A1',
            permission: 'Moderator'
        },
        {
            title: 'A2',
            permission: 'Moderator',
            items: [{
                title: 'A21',
                permission: 'Admin'
            },
            {
                title: 'A22',
                permission: 'Admin'
            }]
        }]
},
{
    title: 'Section B',
    items: [
        {
            title: 'B1',
            permission: 'User'
        },
        {
            title: 'B2',
            permission: 'User'
        },
        {
            title: 'B3',
            permission: 'Admin'
        }]
}]

The user has an array of permissions and I want to filter out all items that are not in the set of permissions of the user.

const userPermissions = ['Moderator', 'User']

I am not searching for a solution that simply loops through the elements; I can code that myself.

CodePudding user response:

Check this:

const navSections = [{title: 'Section A',items: [{title: 'A1',permission: 'Moderator',},{title: 'A2',permission: 'Moderator',items: [{title: 'A21',permission: 'Admin',},{title: 'A22',permission: 'Admin',}]}]},{title: 'Section B',items: [{title: 'B1',permission: 'User',},{title: 'B2',permission: 'User',},{title: 'B3',permission: 'Admin',}]}]

const userPermissions = ['Moderator', 'User']

const navSectionsByPermissions = (arr, permissions, isBase = true) =>
  arr.filter(o => {
    if (o.items) {
      o.items = navSectionsByPermissions(o.items, permissions, false)
    }
    return o.permission && permissions.includes(o.permission) || isBase
  })
  
const result = navSectionsByPermissions(navSections, userPermissions)

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related