猿问

如何过滤数组以匹配数组

我有权限列表:


const all_permissions = [

    {

        permission_id: 1,

        permission_name: "Getting User List",

        permission_method: "GET",

        permission_url: /^\/panel\/user$/

    },

    {

        permission_id: 2,

        permission_name: "Getting User Info",

        permission_method: "GET",

        permission_url: /^\/panel\/user\/[0-9]+$/

    },

    {

        permission_id: 3,

        permission_name: "Testing",

        permission_method: "GET",

        permission_url: /^\/panel\/test\/[a-z]+$/

    }

]


const my_permissions = [1,2]

如何过滤 all_permissions 以仅匹配 my_permissions 中的 id?谢谢


噜噜哒
浏览 129回答 3
3回答

互换的青春

你可以试试Array.prototype.filter()和Array.prototype.includes()const all_permissions = [    {        permission_id: 1,        permission_name: "Getting User List",        permission_method: "GET",        permission_url: /^\/panel\/user$/    },    {        permission_id: 2,        permission_name: "Getting User Info",        permission_method: "GET",        permission_url: /^\/panel\/user\/[0-9]+$/    },    {        permission_id: 3,        permission_name: "Testing",        permission_method: "GET",        permission_url: /^\/panel\/test\/[a-z]+$/    }]const my_permissions = [1,2];const match = all_permissions.filter(p => my_permissions.includes(p.permission_id));console.log(match);

墨色风雨

您可以使用过滤器并包含all_permission使用过滤器循环遍历数组内部过滤器检查permission_id在my_permission数组,如果它的存在,返回true否则返回falseconst all_permissions = [{permission_id: 1,permission_name: "Getting User List",permission_method: "GET",permission_url: /^\/panel\/user$/},{permission_id: 2,permission_name: "Getting User Info",permission_method: "GET",permission_url: /^\/panel\/user\/[0-9]+$/},{permission_id: 3,permission_name: "Testing",permission_method: "GET",permission_url: /^\/panel\/test\/[a-z]+$/}]const my_permissions = [1,2]let op = all_permissions.filter(({permission_id})=> my_permissions.includes(permission_id))console.log(op)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答