Determine the appropriate message based on the size of the array

I am encountering an issue where I have a sample document stored in a mongo atlas database:

{
    "_id": {
        "$oid": "5e517a946364cc48f0ccf1e7"
    },
    "firstName": "checkout1",
    "lastName": "",
    "companyName": "",
    "phoneNumber": null,
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04617c65697468616169656d68446369656d682a676b69">[email protected]</a>",
    "country": "",
    "adress": "",
    "postcode": "",
    "userId": "5daf414818d091616a0d917e",
    "orderedItems": [{
        "_id": "5e03b2072e0c98b9fa62388c",
        "id": 3,
        "title": "Blue shoes",
        "img1": "product4/1.jpg",
        "img2": "product4/2.jpg",
        "cost": 70,
        "color": "blue",
        "quantity": 5
    }],
    "createdAt": {
        "$date": "2020-02-22T19:01:40.228Z"
    },
    "updatedAt": {
        "$date": "2020-02-22T19:01:40.228Z"
    },
    "__v": 0
}

I am looking to send a confirmation message regarding purchased items and their quantity as demonstrated below:

...

    const {
       ...
email,
      orderedItems
    } = req.body;
    var user = await User.findOne({ email: email });
    let newCheckout = await Checkout.create({

      ...
      email,
      ...
      orderedItems,
      userId: user._id
    });
    const htmlEmail = `
    <div>Title of first ordered item: ${newCheckout.orderedItems[0].title}</div>
    `;

    const mailOptions = {
      from: process.env.MY_TEST_EMAIL_ADRESS,
      to: process.env.MY_EMAIL_ADRESS,
      subject: 'new message',
      replyTo: process.env.MY_EMAIL_ADRESS,
      text: process.env.MY_TEST_EMAIL_ADRESS,
      html: htmlEmail
    };
    transporter.sendMail(mailOptions, (err, info) => {});

...

I require this segment of code:

const htmlEmail = `
        <div>Title of first ordered item: ${newCheckout.orderedItems[0].title}</div>
        `;

To structure it similar to React where I can map the orderedItems array to div elements so that the final message would appear something like this (the user would receive all ordered item titles, and the number of div elements would vary based on the array length):

<div>Item: ${newCheckout.orderedItems[0].title}</div>
<div>Item: ${newCheckout.orderedItems[1].title}</div>
<div>Item: ${newCheckout.orderedItems[2].title}</div>

My main query is whether this task can be accomplished without using template engines such as Jade, Pug, Mustache?

Answer ā„–1

Using template engines is optional, but you can loop through the orderedItems:

let emailContent = newCheckout.orderedItems.map(item => `<div>Item: ${item.title}</div>`).join('')

Answer ā„–2

Affirmative.

orderedItems.map(item => `<div>Product: ${item.title}</div>`).join()

If you frequently find yourself revisiting online forums for guidance on advancing your self-made rendering engine, take a moment to explore Knockout.

Using Knockout can ultimately save you time, especially as you continue to add more custom features. Rather than spending excessive time creating workarounds, Knockout simplifies the process of rendering JSON objects on the client side with quick and easy layout modifications. It's a tool worth embracing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The upcoming development does not involve creating an entire HTML webpage using on-demand static site generation (SS

Iā€™m encountering a problem when utilizing getStaticPaths and getStaticProps to create an on-demand SSG for a sharing page. My setup involves Next v12.1.0 and React 17.0.2. After building a specific /[id] page, I can retrieve the data but the HTML output ...

Getting the toState parameter using the $transitions service in the latest version of the ui-router

In my project, I am currently utilizing ui-router version 1.0.0-alpha.3. Please note that the older events have been deprecated in this version. As a result, I am in the process of migrating from: $rootScope.$on('$stateChangeStart', (event, toS ...

Guidance on calling a JavaScript function from a dynamically added control

The Master page includes a ScriptManager. Next, I have a Control with a ScriptManagerProxy and an UpdatePanel. Within the UpdatePanel, I dynamically insert another Control (which also has a ScriptManagerProxy) that needs to run some JavaScript code. In ...

How can a Windows service interact with an Electron application?

Currently, I have a Windows Service set up to regularly check if my application is running. If the application is running, the service then checks for any updates on a server. In the event of an update being available, I am looking for a way for the servic ...

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...

What is the best way to replace multiple strings with bold formatting in JavaScript without losing the previous bolded text?

function boldKeywords(inputString, keywords){ for (var i = 0; i < keywords.length; i++) { var key = keywords[i]; if (key) inputString= inputString.replace(new RegExp(key, 'gi'), '<strong>' + ...

Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database ...

Which is quicker when utilizing jQuery selectors: selecting by .classname or div.classname?

Which is quicker: using $(".classname"). or adding the tag to search for as well? $("div.classname") In my opinion, using just the classname would be faster because jQuery can simply loop through all classnames directly, whereas in the second example i ...

AngularJs Directive continuously returns undefined

Exploring angularjs directives for the first time has been quite a challenge. I can't seem to figure out why my directive isn't working properly as the scope.durationTimeInput always returns undefined no matter what I try. (function () { 'u ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

Avoid loading Google Maps JavaScript library multiple times to improve website performance

I'm facing an issue with loading Google Maps API script twice in a Bootstrap modal through AJAX. Initially, I have a button that, when clicked, triggers an AJAX call to load an HTML file into the modal. The HTML file contains the Google Maps API scrip ...

Accessing the database variable in controller files with Node.js

I am new to node.js and currently using lowdb for my database as I start building my app. In the index.js file, I have set up my Express server along with routes: var express = require('express'); var app = express(); var bodyParser = require(& ...

Creating Hbbtv applications with the help of a Firefox Addon

My curiosity lies in creating hbbtv apps and I am eager to learn how to run and test a complete hbbtv application package, specifically a videoplayer with multiple html pages, utilizing the FireHBBTV plugin on Firefox. Despite my extensive search efforts ...

What is preventing me from implementing my JavaScript event on my EJS code?

Looking to add a click event to the image in my EJS file, here's the EJS code snippet: <div class="container" id="comments"> <div class="row"> <div class="col-lg-12"> <div class="well"> ...

Angularjs could not locate Firebase

I am creating an angularJS application and planning to implement Firebase for simple authentication. Within my index.html file, I have added: <script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script> ...

Discovering identical elements within a list in Python through index-based location scanning

Check out this JavaScript code that can determine whether there are any duplicate elements in an array. function findDuplicates(arr) { let seen = []; for (let i = 0; i < arr.length; i++) { if(seen[arr[i]] === 1) { ...

Cross-Origin Resource Sharing (CORS) for enabling the remote inclusion of JavaScript

I have a unique javascript widget that is designed to be embedded from an external server (e.g. ) The javascript, which contains a simple alert('hello'), is generated by a php script. Upon execution, I include a header like this: <?php heade ...

The file module.js is encountering an error at line 327 because it is unable to locate the module named 'express

Hey there, I'm new to nodejs and whenever I run a file in the command prompt like:- C:\demoData>node demo.js I encounter an error like this: module.js:327 throw err; ^ Error: Cannot find module 'express' at Function.M ...

Examining the version of a node module installed in the local environment and comparing it

One of the reasons I am asking this question is because I have encountered challenges while collaborating with other developers. At times, when other developers update node module versions, I forget to install these new modules after pulling the latest co ...

Showing data from a Node.js Express application in a Jade template file

I am encountering an issue with my simple jade page where not all variables passed from the javascript route are displaying correctly. I have attempted to implement the solution described in this answer, but it seems to be ineffective in my case. My goal i ...