[英]includes function Iterate over all array in javascript
I have a code which iterates over an array of Objects and checks if it contains admin word.If it contains then I want to call Admin API and if not then I want to call Non-Admin API.我有一个代码,它遍历一个对象数组并检查它是否包含管理员字。如果它包含,那么我想调用管理员 API,如果没有,那么我想调用非管理员 API。 The code works fine however the issue is while iterating it say authority contains 5 Objects and 3rd index contains admin keyword then the logic calls 2 non-admin api and 1 admin api and then again 2 non-admin apis.
代码工作正常,但问题是在迭代时说权限包含 5 个对象,第三个索引包含 admin 关键字,然后逻辑调用 2 个非管理员 api 和 1 个管理员 api,然后再调用 2 个非管理员 api。 Is there a better way to write the code that the logic will check whether the whole array contains admin keyword or not and call admin API or Non-Admin API only once.
有没有更好的方法来编写逻辑将检查整个数组是否包含 admin 关键字并仅调用一次 admin API 或 Non-Admin API 的代码。
if (tempAuth && tempAuth.length > 0) {
this.auth = tempAuth.filter(x => {
if (x.authority.includes('admin')) {
// Admin API
this.getalldetails();
}
else {
// Non Admin API
this.getUserdetails();
}
});
One option is to use the some
method to check if the auth criteria is ever met.一种选择是使用
some
方法检查是否满足身份验证条件。 Then you can use that boolean value to determine what to do next.然后您可以使用该 boolean 值来确定下一步要做什么。
if (tempAuth && tempAuth.length > 0) {
this.auth = tempAuth.some(x => x.authority.includes('admin'));
if (this.auth) {
this.getalldetails();
} else {
this.getUserdetails();
}
}
You can use some()
method to determine whether at least one element in the array tempAuth
includes authority
as admin.您可以使用
some()
方法来确定数组tempAuth
中的至少一个元素是否包含管理员authority
。 If yes, then we set getalldetails
to this.auth
else we pass getUserdetails
如果是,那么我们将
getalldetails
设置为this.auth
否则我们传递getUserdetails
if (tempAuth && tempAuth.length > 0) {
var found = tempAuth.some(x => x.authority.includes('admin'));
this.auth = found ? this.getalldetails() : this.getUserdetails();
}
The array function some
returns a boolean if the condition is true for at least 1 item.如果至少一项条件为真,则数组 function
some
返回 boolean。
if (tempAuth && tempAuth.length > 0) {
const isAdmin = tempAuth.some(x => x.authority.includes('admin'));
if (isAdmin) {
// Admin API
this.getalldetails();
} else {
// Non Admin API
this.getUserdetails();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.