javascript 我想在比较两个数组后返回true或false

92vpleto  于 2022-10-30  发布在  Java
关注(0)|答案(3)|浏览(180)

我想在比较两个数组后返回true或false。

此处为第一个数组:

const permissionsArray = [
  {
    "groupName": "User",
    "permissions": [
      "Permissions.Users.View",
      "Permissions.Users.Create",
      "Permissions.Users.Edit",
      "Permissions.Users.Delete"
    ]
  }, {
    "groupName": "Role",
    "permissions": [
      "Permissions.Roles.View",
      "Permissions.Roles.Create",
      "Permissions.Roles.Edit",
      "Permissions.Roles.Delete"
    ]
  },
]

此处为包含权限的对象数组:

const userPermissionArray = 
  {
    "id": "cdfda4d3-ea1a-4662-a611-2d2e52b772b0",
    "name": "ABP Manager",
    "description": "ABP Manager",
    "usersCount": 4,
    "isActive": false,
    "permissions": [
      "Permissions.Users.View",
      "Permissions.Users.Create",
      "Permissions.Users.Edit",
      "Permissions.Users.Delete"
    ]
  }

我希望比较**[权限数组.权限][用户权限数组.权限]**。
我试过了,但失败了。我的代码是:

console.log(
  userPermissionArray.permissions
    .map(roleItem => roleItem === userPermissionArray
      .map(item  => item.permissions.map(item => item))
    )
);

我试图返回“真”或“假”。

ruarlubt

ruarlubt1#

您可以flat权限列表以便于比较,然后使用some函数检查是否存在任何条目

let flatPermissions = permissionsArray.map(e => e["permissions"]).flat();

let result = userPermissionArray.permissions.some(i => flatPermissions.includes(i));

console.log(result);
g2ieeal7

g2ieeal72#

试着这样比较:

let permissionsA = [
        "Permissions.Users.View",
        "Permissions.Users.Create",
        "Permissions.Users.Edit",
        "Permissions.Users.Delete"
    ]

    let permissionsB = [
        "Permissions.Users.View",
        "Permissions.Users.Create",
        "Permissions.Users.Edit",
    ]

    let rs = permissionsA.reduce((a, b) => {
        return {
            ...a,
            [b]: permissionsB.includes(b)
        }
    }, {})

    console.log(rs)

/*  
 {
  Permissions.Users.Create: true,
  Permissions.Users.Delete: false,
  Permissions.Users.Edit: true,
  Permissions.Users.View: true
 } */
iih3973s

iih3973s3#

let x = ['a', 'b', 'c', 'd']
    let y = ['b', 'c']
    let cont=[]
    let rs = x.reduce((a, b) => {
      return {
          ...a,
          [b]: y.includes(b)
      }
    }, {})

    for(let i=0; i < x.length; i++){ 
      if((rs[x[i]])){
        cont.push({
          data: x[i],
          selected : true
        })
      }else
      cont.push({
        data: x[i],
        selected : false
      })
    }
console.log(cont)

相关问题