首页 > 解决方案 > 结合 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 个条件的条件。

  1. nextAction数组应该是非空的 。
  2. userList数组不应包含该元素null
  3. 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)

预期结果为真,而我未定义。

标签: javascriptforeachecmascript-6

解决方案


你可以通过some & find做到这一点:

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


推荐阅读