javascript - 结合 es6 函数 every 和 sum 并返回布尔值
问题描述
我有一个 JSON 响应
{
"nextAction": [{
"userList": [{
"id": 8,
"email": "testemail@gmail.com",
"name": "John Doe"
}],
"buttonLabel": "Finalize Now"
},
{
"userList": [{
"id": 10,
"email": "newemail@gmail.com",
"name": "Test User"
}],
"buttonLabel": "Start Now"
}
]
}
userList
数组有时包含null
对象。我正在处理满足以下 3 个条件的条件。
nextAction
数组应该是非空的 。userList
数组不应包含该元素null
。currentUser
应该存在于userList
数组中。
const data = [{
"userList": [{
"id": 8,
"email": "testemail@gmail.com",
"name": "John Doe"
}],
"buttonLabel": "Finalize Now"
},
{
"userList": [{
"id": 10,
"email": "newemail@gmail.com",
"name": "Test User"
}],
"buttonLabel": "Start Now"
}]
function checkForMyNextActions(myNextActions, currentUser) {
const checkUsername = obj => obj.email === currentUser;
return (myNextActions.forEach((myAction, index) => {
(myAction.userList.length &&
myAction.userList.every(userList =>
userList !== null) &&
myAction.userList.some(checkUsername)
)
}))
}
var result = checkForMyNextActions(data, "testemail@gmail.com")
console.log(result)
预期结果为真,而我未定义。
解决方案
var obj = {
"nextAction": [{
"userList": [{
"id": 8,
"email": "testemail@gmail.com",
"name": "John Doe"
}],
"buttonLabel": "Finalize Now"
}]
}
const getUser = (usr) => obj.nextAction.some(({
userList
}) =>
userList ? (userList.every(userList => userList !== null) &&
userList.find(y => y.email === usr)) : false)
console.log(getUser("testemail@gmail.com")) // true
console.log(getUser("test@gmail.com")) // false
方法的好处是,如果一个元素与我们的例子中是电子邮件some
内部的条件匹配,它会返回布尔值。find
您可以走得更远,让函数接受一个匹配的字段,如下所示:
var obj = { "nextAction": [{ "userList": [{ "id": 8, "email": "testemail@gmail.com", "name": "John Doe" }], "buttonLabel": "Finalize Now" }] }
const getUser = (field="email", usr) => obj.nextAction.some(({userList}) =>
userList ? userList.find(y => y[field] === usr): false)
console.log(getUser("email", "testemail@gmail.com")) // true
console.log(getUser("name", "John Doe")) // true
推荐阅读
- javascript - ParseInt 丢弃数字
- node.js - 如何向 socketIO 添加请求和响应
- unix - 在连接 UNIX 套接字端之前打开 socat 连接的 TCP 端
- c - 为什么 OpenMP 不能加速我的 C 程序?
- java - 在 Netbeans 中解析 JSON 数据时遇到问题
- html - flex-grow 不起作用,我做错了什么?
- php - PHP - Mysql 查询问题。执行查询后,我的 PHP 脚本就停在那里
- sql - 我可以使用子查询而不是加入表吗?
- r - 使用 purr 和 dplyr 将函数应用于列的子集
- javascript - 如何处理错误 - Codesandbox 的 React 应用程序中的“无法获取”