ES6 为多个数组运行不同的函数

我有一个sendEmail函数需要根据用户在数组中的位置发送不同的电子邮件。例如,我有以下数据:


  { download: 'Release sale. 50% off!',

    user: 'test1@gmail.com' },

  { download: 'Release sale. 50% off!',

    user: 'test2@gmail.com' },

  { download: 'Release sale. 50% off!',

    user: 'test3@gmail.com' },

  { download: 'Release sale. 50% off!',

    user: 'test4@gmail.com' } 

]

  { download: 'Test',

    user: 'test5@gmail.com' 

  } 

]

对于每个数组,我需要累积所有user电子邮件和download字符串并运行以下函数:


await transporter.sendMail({

    from: '"Test" <noreply@test.com>',

    to: [email array here],

    subject: "Here is your file",

    text: `Here is your download: ${download}`

  })


HUH函数
浏览 198回答 2
2回答

慕无忌1623718

您可以将数组组合成一个数组并对其进行迭代,sendMail()为每个元素调用您的方法。const users1 = [{&nbsp; &nbsp; download: 'Release sale. 50% off!',&nbsp; &nbsp; user: 'test1@gmail.com'&nbsp; },&nbsp; {&nbsp; &nbsp; download: 'Release sale. 50% off!',&nbsp; &nbsp; user: 'test2@gmail.com'&nbsp; },&nbsp; {&nbsp; &nbsp; download: 'Release sale. 50% off!',&nbsp; &nbsp; user: 'test3@gmail.com'&nbsp; },&nbsp; {&nbsp; &nbsp; download: 'Release sale. 50% off!',&nbsp; &nbsp; user: 'test4@gmail.com'&nbsp; }];const users2 = [{&nbsp; download: 'Test',&nbsp; user: 'test5@gmail.com'}];const allUsers = [...users1, ...users2];const groupedUsers = allUsers.reduce((acc, u) => {&nbsp; const group = acc.find(x => x.download === u.download);&nbsp; if (group) {&nbsp; &nbsp; group.users.push(u.user);&nbsp; &nbsp; return acc;&nbsp; }&nbsp; return [...acc, {&nbsp; &nbsp; download: u.download,&nbsp; &nbsp; users: [u.user]&nbsp; }];}, []);console.log(groupedUsers)使用groupedUsers上面的列表,您应该能够根据download属性向用户组发送电子邮件。groupedUsers.forEach(async group => {&nbsp; await transporter.sendMail({&nbsp; &nbsp; from: '"Test" <noreply@test.com>',&nbsp; &nbsp; to: group.users,&nbsp; &nbsp; subject: "Here is your file",&nbsp; &nbsp; text: `Here is your download: ${group.download}`&nbsp; });});我使用了 spread ( ...) 运算符来组合数组,但concat()如果您愿意,也可以使用。const allUsers = users1.concat(users2);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript