如何发送仅包含值的对象键值对?

问题描述 投票:0回答:2

我正在创建一个在线作业应用程序,当它被提交时,通过nodemailer和mailgun向招聘经理发送电子邮件。该应用程序相当长,并非所有字段都是必需的。目前,我已将其设置为通过电子邮件将所有键值对发送给招聘经理,但如果该字段为空,我宁愿将该键值对保留在电子邮件之外。我怎么能做到这一点?

这是我的nodemailer代码:

const nodemailer = require('nodemailer');
const mailgun = require('nodemailer-mailgun-transport');
const debug = require('debug')('app:mail');

const auth = {
    auth: {
       api_key: '**************************************',
       domain: '*************************.mailgun.org' 
    }
};

const transporter = nodemailer.createTransport(mailgun(auth));

function sendAppliedEmail(applicant) {
  let html = '<div style="background: url(****************************************) center center/cover no-repeat; background-size: auto;">'
  html += '<img src="**************************" alt="logo" style="margin: 0 auto;">';
  html += '<h2 style="color: #f49842; text-align: center">New Applicant</h2>'
  html += '<ul>';

  Object.entries(applicant).forEach(([key, value]) => {

    html += `<li>${key.replace(/([a-z])([A-Z])/g, `$1 $2`).toUpperCase().fontcolor('green')}: ${value}</li>`;
  });

  html += '</ul></div>';

  const mailOptions = {
    from: '[email protected]',
    to: '[email protected], [email protected], [email protected]',
    subject: 'New Applicant to Tropical Sno',
    html
  };

  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      debug(`Error: ${err}`);
    } else {
      debug(`Info: ${info}`);
    }
  });
}

module.exports = sendAppliedEmail;
javascript key-value mailgun nodemailer
2个回答
2
投票

您可以使用Array.Prototype.Filter获取其值不为空或未定义的所有对,然后在该已过滤的数组上创建html。

Object.entries(applicant).filter(([key,value])=>value).forEach(([key, value]) => {

    html += `<li>${key.replace(/([a-z])([A-Z])/g, `$1 $2`).toUpperCase().fontcolor('green')}: ${value}</li>`;
  });

1
投票

你可以使用条件(if

Object.entries(applicant).forEach(([key, value]) => {
  if(value) {    
    html += `<li>${key.replace(/([a-z])([A-Z])/g, `$1 $2`).toUpperCase().fontcolor('green')}: ${value}</li>`;
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.