亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ES6 為多個數組運行不同的函數

ES6 為多個數組運行不同的函數

HUH函數 2021-09-30 15:18:15
我有一個sendEmail函數需要根據用戶在數組中的位置發送不同的電子郵件。例如,我有以下數據:[   { download: 'Release sale. 50% off!',    user: '[email protected]' },  { download: 'Release sale. 50% off!',    user: '[email protected]' },  { download: 'Release sale. 50% off!',    user: '[email protected]' },  { download: 'Release sale. 50% off!',    user: '[email protected]' } ][   { download: 'Test',    user: '[email protected]'   } ]對于每個數組,我需要累積所有user電子郵件和download字符串并運行以下函數:await transporter.sendMail({    from: '"Test" <[email protected]>',    to: [email array here],    subject: "Here is your file",    text: `Here is your download: ${download}`  })
查看完整描述

2 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

您可以將數組組合成一個數組并對其進行迭代,sendMail()為每個元素調用您的方法。


const users1 = [{

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

    user: '[email protected]'

  },

  {

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

    user: '[email protected]'

  },

  {

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

    user: '[email protected]'

  },

  {

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

    user: '[email protected]'

  }

];


const users2 = [{

  download: 'Test',

  user: '[email protected]'

}];


const allUsers = [...users1, ...users2];


const groupedUsers = allUsers.reduce((acc, u) => {

  const group = acc.find(x => x.download === u.download);


  if (group) {

    group.users.push(u.user);

    return acc;

  }


  return [...acc, {

    download: u.download,

    users: [u.user]

  }];

}, []);


console.log(groupedUsers)

使用groupedUsers上面的列表,您應該能夠根據download屬性向用戶組發送電子郵件。


groupedUsers.forEach(async group => {

  await transporter.sendMail({

    from: '"Test" <[email protected]>',

    to: group.users,

    subject: "Here is your file",

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

  });

});

我使用了 spread ( ...) 運算符來組合數組,但concat()如果您愿意,也可以使用。const allUsers = users1.concat(users2);


查看完整回答
反對 回復 2021-09-30
  • 2 回答
  • 0 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號