数组包含其他数组的值

Array contains value of other array

所以我正在使用 Angular,我得到了一个表格,我可以在其中输入一些电子邮件。 我发送这些电子邮件,如果它们已经存在,如果 return 一条错误消息,其中包含正在使用的电子邮件。

表单中的对象如下所示:

0: Object 
  email: "email@gmail.com"
  name: "My Name"
1: Object 
  email: "other@email.com"
  name: "My Other Name"

例如,如果 email@gmail.com 已经在使用中,我会从我的 API 中检索到以下错误:

data: Array[1]
   0: Object
     email: "email@gmail.com"
message: "Some email addresses are already in use."

我设法使用了 underscore.js 中的 pluck,在那里我得到了一组电子邮件。

这就是我卡住的地方。我想检查来自我的表单对象的电子邮件是否包含来自已用电子邮件数组的值。如果它确实包含一个值,我想将 used: true 添加到相关的表单对象中。

假设 email@gmail.com 正在使用中,我希望我的表单对象是:

0: Object 
  email: "email@gmail.com"
  name: "My Name"
  used: true
1: Object 
  email: "other@email.com"
  name: "My Other Name"

假设您的数据结构看起来像那样,您可以调用 API,获取响应,然后遍历您的电子邮件数组,检查它们是否出现在 [= 的响应中21=]。

为此,您可以使用简单的 for 循环,甚至 Array.profotype.forEach 方法。假设 for 语句是最稳定的方法,我给你举个例子:

// myData is the data array containing the various objects which have email and name
// myResponse is the response object retrieved from your API call

for (var i=0; i < myResponse.data.length; i++) {
    for (var j=0; j < myData.length; j++) {
        if (myResponse.data[i].email == myData[i].email) {
            myData[i].used = true;
        }
    }
}

执行上述代码后,您的表单数据对象将如下所示:

myData = [
    { 
        email: "email@gmail.com",
        name: "My Name",
        used: true
    },
    {
        email: "other@email.com",
        name: "My Other Name"
    }
];