javascript - 如果找到具有正确属性的obj,则js返回true

标签 javascript arrays object

let userScopes = [
  {
    scope: 'user',
    actions: ['create', 'read', 'update'],
  },
];

function checked(scope, actions) {
  return !!~userScopes.find(
    _scope =>
      _scope.scope === scope && _scope.actions.lastIndexOf(actions) !== -1
  );
}

console.log(checked("user","create"));//true
console.log(checked("users","create"));//false
console.log(checked("user","creat"));//false
console.log(checked("make","create"));//false

我必须确保如果找到具有以下属性的对象,则它返回 true,否则返回 false。

但是它行不通,有什么建议吗?

最佳答案

您可以使用 Array#some 查看和 Array#includes .

function checked(scope, action) {
    return userScopes.some(o => o.scope === scope && o.actions.includes(action));
}

let userScopes = [{ scope: 'user', actions: ['create', 'read', 'update'] }];

console.log(checked("user", "create"));  //  true
console.log(checked("users", "create")); // false
console.log(checked("user", "creat"));   // false
console.log(checked("make", "create"));  // false

关于javascript - 如果找到具有正确属性的obj,则js返回true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57850743/

相关文章:

javascript - 为什么我的 html5 canvas 动画如此闪烁?

javascript - AngularJS 范围变量在某处使用 $http 时不起作用

arrays - 如何在 Perl 中按列对数组或表进行排序?

javascript - 为什么在函数中覆盖整个数组不会替换它,但逐个元素覆盖却可以?

objective-c - NSArray 循环抓取对象

java - 由于java中的继承而创建了多少个对象?

javascript - 在 Tumblr 上为 HTML 标签添加事件监听器

c - 从 int 数组中删除值

Javascript 对象路由映射

javascript - 我如何在 typescript 中声明一个 'monkey patched' 原型(prototype)