简体   繁体   中英

How to send object key value pairs that contain values only?

I am creating an online job application that when it is submitted sends an email through nodemailer and mailgun to the hiring manager. The application is fairly long and not all fields are required. Currently, I have it set up to send all key value pairs in an email to the hiring manager but if the field is left empty I would prefer to just leave that key value pair out of the email. How could I accomplish this?

here is my nodemailer code :

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: 'info@example.com',
    to: 'sample@example.com, sampleme@example.com, sampletwo@example.com',
    subject: 'New Applicant to Tropical Sno',
    html
  };

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

module.exports = sendAppliedEmail;

You can use Array.Prototype.Filter to get all pairs whose value is not empty or undefined and then create html on that filtered array.

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>`;
  });

You can use condition ( 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>`;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM