【问题标题】:Array and object filter javascript数组和对象过滤器 javascript
【发布时间】:2021-08-09 16:40:46
【问题描述】:

我有以下数组

permissionList: [
        {
            name: "Database",
            permissions: [
                {
                    id: "610c3b02e5e2dc586c6bfbbd",
                    key: "Database/View",
                    name: "View Database",
                    description: "permission for view database module",
                    createdAt: "",
                    updatedAt: "",
                },
                {
                    id: "610c3b02e5e2d3w586c6bfbfs",
                    key: "Database/Add",
                    name: "Add Database",
                    description: "permission for Add database module",
                    createdAt: "",
                    updatedAt: "",
                },
            ],
        },
        {
            name: "Project",
            permissions: [
                {
                    id: "610c3b02e5e2dc586c6bfbbd",
                    key: "Project/View",
                    name: "View Project",
                    description: "permission for view Project module",
                    createdAt: "",
                    updatedAt: "",
                },
                {
                    id: "610c3b02e5e2d3w586c6bfbfs",
                    key: "Project/Add",
                    name: "Add Project",
                    description: "permission for Add Project module",
                    createdAt: "",
                    updatedAt: "",
                },
            ],
        },
    ],

当有人进入数据库/视图时,应该过滤如下。

permissionList: [
        {
            name: "Database",
            permissions: [
                {
                    id: "610c3b02e5e2dc586c6bfbbd",
                    key: "Database/View",
                    name: "View Database",
                    description: "permission for view database module",
                    createdAt: "",
                    updatedAt: "",
                }
            ],
        },
]

【问题讨论】:

    标签: javascript arrays javascript-objects


    【解决方案1】:

    您可以使用两个简单的功能进行过滤,一个过滤内部权限列表,第二个如果内部列表不为空,则列出外部权限列表。

    // Function to filter inner permissions if their key is equals to the requested key
    function innerFilter(permissions, key) {
       return permissions.filter(permission => permission.key == key);
    }
    
    
    // Function to be called with the permission list. It filter inner
    // permissions, than it consider only not empty inner permissions
    function outerFilter(list, key) {
        return list
          // make a copy of original items with a list of permissions
          // satisfying the requested key
          .map(item => { 
             return {  
                ...item, 
                permissions: innerFilter(item.permissions, key) 
             } 
          })
          // filter the items having at least 1 inner permission
          // satisfying the requested key
          .filter(item => item.permissions.length > 0)
    }
    

    并使用 outerFilter 函数调用它

    var searchedList = outerFilter(permissions, "Database/View");
    

    请考虑此代码尚未经过测试,因此可能会出现拼写错误,请作为一个想法。如有必要,添加对 null 或未定义值的测试。

    最终你可以将这两个函数组合成一个函数,如下所示:

    // Function to be called with the permission list. It filter inner
    // permissions, than it consider only not empty inner permissions
    function filterByPermissionKey(list, key) {
        return list
          // make a copy of original items with a list of permissions
          // satisfying the requested key
          .map(item => { 
             return {  
                ...item, 
                // Extract the sublist of permissions having the requested key
                permissions: item.permissions.filter(permission => permission.key == key)
             } 
          })
          // filter the items having at least 1 inner permission
          // satisfying the requested key
          .filter(item => item.permissions.length > 0)
    }
    

    【讨论】:

    • 非常感谢
    • @GihanPrimesha 请为所有符合您要求的答案投票,并选择其中一个作为接受的答案
    【解决方案2】:

    const permissionList = [
            {
                name: "Database",
                permissions: [
                    {
                        id: "610c3b02e5e2dc586c6bfbbd",
                        key: "Database/View",
                        name: "View Database",
                        description: "permission for view database module",
                        createdAt: "",
                        updatedAt: "",
                    },
                    {
                        id: "610c3b02e5e2d3w586c6bfbfs",
                        key: "Database/Add",
                        name: "Add Database",
                        description: "permission for Add database module",
                        createdAt: "",
                        updatedAt: "",
                    },
                ],
            },
            {
                name: "Project",
                permissions: [
                    {
                        id: "610c3b02e5e2dc586c6bfbbd",
                        key: "Project/View",
                        name: "View Project",
                        description: "permission for view Project module",
                        createdAt: "",
                        updatedAt: "",
                    },
                    {
                        id: "610c3b02e5e2d3w586c6bfbfs",
                        key: "Project/Add",
                        name: "Add Project",
                        description: "permission for Add Project module",
                        createdAt: "",
                        updatedAt: "",
                    },
                ],
            },
        ];
        
        console.log('Permission List Before ==>', permissionList);
        
        const newList = permissionList.filter(eachObj => eachObj.name === "Database");
        console.log('New List ==>', newList);

    您可以对 Javascript 中的数组执行上述 .filter() 选项

    【讨论】:

    • 我想过滤掉对象中的数组,而不是你提到的。
    【解决方案3】:

    const permissionList = [{
        name: "Database",
        permissions: [{
            id: "610c3b02e5e2dc586c6bfbbd",
            key: "Database/View",
            name: "View Database",
            description: "permission for view database module",
            createdAt: "",
            updatedAt: "",
          },
          {
            id: "610c3b02e5e2d3w586c6bfbfs",
            key: "Database/Add",
            name: "Add Database",
            description: "permission for Add database module",
            createdAt: "",
            updatedAt: "",
          },
        ],
      },
      {
        name: "Project",
        permissions: [{
            id: "610c3b02e5e2dc586c6bfbbd",
            key: "Project/View",
            name: "View Project",
            description: "permission for view Project module",
            createdAt: "",
            updatedAt: "",
          },
          {
            id: "610c3b02e5e2d3w586c6bfbfs",
            key: "Project/Add",
            name: "Add Project",
            description: "permission for Add Project module",
            createdAt: "",
            updatedAt: "",
          },
        ],
      },
    ];
    
    console.log('Permission List Before ==>', permissionList);
    
    let permissionsOfEachObj = [];
    
    let keys = [];
    
    permissionList.forEach(obj => {
      keys = Object.keys(obj);
    });
    
    console.log('Keys ==>', keys);
    
    keys.forEach((key) => {
      if(key === 'permissions') {
        permissionList.forEach(obj => {
          permissionsOfEachObj.push(obj[key]);
        })
      }
    });
    
    console.log('Permissions Of Each Object ==>', permissionsOfEachObj);
    
    permissionsOfEachObj = permissionsOfEachObj.flat();
    console.log('Permissions Of Each Object after Flatting ==>', permissionsOfEachObj);
    
    const databaseOrView = permissionsOfEachObj.filter(eachObj => eachObj.key === "Database/View");
    console.log('Final Output ==>', databaseOrView);

    好的。我现在明白了这个问题。请立即在此处检查所需的输出。您拥有检查答案所需的控制台日志。

    【讨论】:

    • 非常感谢
    • @GihanPrimesha 如果您认为它解决了您的问题,请批准答案。
    【解决方案4】:

    只有一种解决方案拒绝屈服于这种新的伪函数式编程宗教。
    在这种函数中没有任何通用或可重用的东西,所以在不变性和诸如此类方面没有任何好处。没有其他人会使用它,所以它要么在此时此地起作用,要么不起作用。

    与往常一样,使用纯 JavaScript 可以让您通过添加琐碎、自然的优化和安全检查来编写更快、更安全的代码,例如:

    • 避免大量无用的浅拷贝
    • 得到结果后缩短循环
    • 禁止获得多个结果(密钥应该是唯一的)
    • 禁止查询不存在的键

    顺便说一句,你肯定有你的理由,但是一旦你得到一个许可,外层数据只是多余的行李。
    您也可以返回实际的权限记录,有或没有(浅)副本,具体取决于您是否打算改变结果。
    在这种特殊情况下,您似乎想用过滤器的结果替换初始列表,因此创建中间不可变对象是没有意义的。

    function GetPermissionByKey (list, key)
    {
        // if you want to check for unicity of key
        // let result = undefined;
        for (item of list) {                                     // browse all items
            for (permission of item.permissions) {               // browse all keys of each item
                if (permission.key == key) {                     // found the key
                    // ...variant to enforce key uniqueness:
                    // if (result !== undefined) throw 'duplicate key ' + key;
                    // result = [{...item, permissions: [{...permission}]}];
                    return [{...item, permissions: [{...permission}]}]; // full deep copy
                    // ...or a shallow copy
                    // return [{...item, permissions: [permission]}];
                    // ...or you might just drop the excess luggage:
                    // return permission;
                    // ...or return a shallow copy if you really want one:
                    // return {...permission};
                }
            }
        }
        // ...if you checked for unicity of keys
        // return result ?? []; // return an empty array if key was not found
        // ...or without unicity check
        return [];
        // ...or consider using a wrong key a program error
        // throw 'key not found ' + key;
    }
    

    使用您的示例输入的示例输出:

    var res = GetPermissionByKey(permissionList,"Database/View");
    console.log(`${JSON.stringify(res,undefined,2)}`)
    
    [
      {
        "name": "Database",
        "permissions": [
          {
            "id": "610c3b02e5e2dc586c6bfbbd",
            "key": "Database/View",
            "name": "View Database",
            "description": "permission for view database module",
            "createdAt": "",
            "updatedAt": ""
          }
        ]
      }
    ]
    

    【讨论】:

      【解决方案5】:

      试试这个:

      const permissionList = [
              {
                  name: "Database",
                  permissions: [
                      {
                          id: "610c3b02e5e2dc586c6bfbbd",
                          key: "Database/View",
                          name: "View Database",
                          description: "permission for view database module",
                          createdAt: "",
                          updatedAt: "",
                      },
                      {
                          id: "610c3b02e5e2d3w586c6bfbfs",
                          key: "Database/Add",
                          name: "Add Database",
                          description: "permission for Add database module",
                          createdAt: "",
                          updatedAt: "",
                      },
                  ],
              },
              {
                  name: "Project",
                  permissions: [
                      {
                          id: "610c3b02e5e2dc586c6bfbbd",
                          key: "Project/View",
                          name: "View Project",
                          description: "permission for view Project module",
                          createdAt: "",
                          updatedAt: "",
                      },
                      {
                          id: "610c3b02e5e2d3w586c6bfbfs",
                          key: "Project/Add",
                          name: "Add Project",
                          description: "permission for Add Project module",
                          createdAt: "",
                          updatedAt: "",
                      },
                  ],
              },
          ]
      
      console.log({name: permissionList[0].name, permissions: [permissionList[0].permissions[0]]})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-15
        • 2019-10-15
        • 2022-07-13
        • 1970-01-01
        • 2018-07-17
        • 1970-01-01
        • 2017-10-19
        相关资源
        最近更新 更多