Condensing an Array of Objects into a solitary result

Hey there, I'm currently exploring the most efficient method to accomplish a task. The data I am dealing with looks something like this:

[
    {
    name: 'email.delivered',
    programme: 'Email One',
    timestamp: 2022-03-24T18:06:02.000Z,
    "payload":{
          "id":"bcabca7c-a5d5-4e02-b247-2292240ffc77",
      },
    },
    {
    name: 'interaction.click',
    programme: 'Email One',
    timestamp: 2022-03-24T18:06:02.000Z,
    "payload":{
        "correlation":{
           "channel":"email",
           "messageId":"bcabca7c-a5d5-4e02-b247-2292240ffc77",
        },
        "metadata":{
            "customerId":"9999999111",
            "programName":"Email One"
        }
      },
    },
    ...
]

The event names include delivered, failed, expired, or click. The programmes serve as categories for organization. Currently, my code snippet (simplified) performs certain checks in the following manner:

emails.forEach((record) => {
  const data = JSON.parse(record.data);
  if (data?.name === 'email.delivered') {
    const id = data?.payload?.id;
    if (!deliverDates[id]) deliverDates[id] = record.timestamp;
    deliveredMap.set(programme, (deliveredMap.get(programme) || 0) + 1);
    return;
  }
  if (data?.name === 'email.click') {
    const id = data?.payload?.correlation?.messageId;
    if (id) {
      const deliveryDate = new Date(deliverDates[id]);
      if (deliveryDate.getTime() > Date.now() - 1209600000) {
        const programme = record?.programme;
        clicksMap.set(programme, (clicksMap.get(programme) || 0) + 1);
      }
    }
  }
});

The issue lies in having two separate Maps instead of returning a single Object with the programme as the key. My goal is to tally up all event types for each programme, resembling the desired structure below:

{
  'Email One': {
    delivered: 315,
    failed: 18,
    expired: 14,
    click: 27,
  },
  'Email Two': {
    delivered: 542,
    failed: 322,
    expired: 33,
    click: 22,
  }
  ...
}

Any suggestions on how to achieve this outcome efficiently would be greatly appreciated.

Cheers!

Answer №1

Utilize a helper function to track the occurrence of events:

const eventCountsByProgramme = {};
function recordOccurrence(programme, event) {
  const eventCounts = (eventCountsByProgramme[programme] ??= {});
  eventCounts[event] = (eventCounts[event] ?? 0) + 1;
}

Then make use of

recordOccurrence(programme, 'delivered');

in place of

deliveredMap.set(programme, (deliveredMap.get(programme) || 0) + 1);

and

recordOccurrence(programme, 'click');

instead of

clicksMap.set(programme, (clicksMap.get(programme) || 0) + 1);

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

How can I cut an array by value in Vue?

I am working on a component that has a list of objects and I need to implement functionality where, when toggled, the objects' title prop is either added to or removed from an array. Adding the value was easy to do, but removing it has proven challeng ...

"Enhance your website with the powerful combination of SweetAlert

I'm having trouble getting my ajax delete function to work with SweetAlert. I can't seem to find the error in my code. Can someone help me figure out how to fix it? function deletei(){ swal({ title: 'Are you sure?', ...

Spring MVC applications might experience slow loading times when loading RequireJS libraries

Recently, I integrated RequireJS into my Spring MVC application to manage dependencies for various libraries, including jQuery and jQuery UI. Although I have successfully implemented it, I am facing an issue whenever the page is loaded or refreshed. Initia ...

What is the best way to anticipate a return phone call?

Looking to retrieve the largest date from a folder by reading its contents. https://i.stack.imgur.com/KYren.png Here is the code snippet to read the folder, extract filenames, and determine the largest date (excluding today): async function getLastDate ...

The mesh's position has become invalid due to the dynamic change in vertices' positions

When attempting to create a mesh using PlaneGeometry, I encountered an issue where after dynamically changing the geometry's vertices, the mesh's position and rotation were no longer correct. Is there a way to update these properties properly to ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

Verify whether a class or id is present in the HTML response obtained from an AJAX request

Is there a way to check the content of HTML returned by an AJAX call before rendering it to avoid any flickering effect? I am aware of using hasClass() to check for classes, but in this scenario, the AJAX response is returning HTML. I can append the HTML ...

Guide on transforming 3D obj files into particles using three.js

I've been experimenting with particles in three.js, but I've encountered an issue when trying to convert an obj file (3D model) into particles. Here are the code snippets I've been working with, but so far all my attempts have failed. Does ...

Trouble encountered while trying to show information on Tooltip using AngularStrap

I've been attempting to show some information in a Tooltip, but all I see is the Title displayed like this: Below is the HTML code where I'm calling it: <button class="btn btn-primary" type="bu ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

A guide to sharing session variables with express views

Struggling to access session variables in EJS views and encountering various challenges. To locally access req.session, I've implemented middleware as outlined in this guide on accessing Express.js req or session from Jade template. var express = re ...

Tips for Incorporating xmlhttp.responseText in If Statements

This is the code snippet from my save_custLog_data.php file: <?php $a = $_GET['custEmail']; $b = $_GET['pswrd']; $file = '/home/students/accounts/s2090031/hit3324/www/data/customer.xml'; if(file_exists($fi ...

"Spin an image using Javascript when it is shown on the

I've got a script that shows an image when we are attacked by a monster. The image is initially set to display="none", but switches to display="" when a monster appears. What I'm looking to do is make the image rotate 360° when it changes from ...

Can you explain the role of the faceVertexUV array within the three.js Geometry class?

Currently, I am utilizing three.js to create curved shapes using parametric functions. Within the THREE.js javascript file, there is a function called THREE.ParametricGeometry that continuously adds 2D vectors to the faceVertexUvs array. I am curious abo ...

results vary when using both a while loop and callback

I'm having an issue with my while loop when filtering data from mongodb. Even though I should be getting three entries logged to the console, only one entry is making it to the callback function. Can anyone explain why this is happening? while(i--) { ...

Checking for any lint errors in all JavaScript files within the project package using JSHint

Currently, I am utilizing the gulp task runner to streamline my workflow. My goal is to implement JsHint for static code analysis. However, I have encountered a setback where I can only run one file at a time. Upon npm installation, "gulp-jshint": "~1.11. ...

Processing JSON data from an array in PHP

Currently, my code involves utilizing an AJAX request to retrieve data from a database dynamically. The data received is processed by the PHP function json_encode() before being sent back to AJAX. Upon receiving the data through the AJAX request, it is for ...

A guide on converting HTML and CSS to a PDF file using JavaScript

I'm facing a challenge where I need to create a custom quote in pdf using data retrieved in JavaScript and sent in HTML. However, the issue is that no library supports CSS for the PDF generation process. After some research, I came across HTML2CANVAS ...

The canvas element automatically removes itself after being resized within an HTML5/JavaScript environment

I created a canvas that is interactive and responsive to screen size. However, I encountered an issue where the canvas clears itself when the browser is resized by just one pixel. Is there a way to prevent this from happening? I have included code in my sc ...

Utilizing data retrieval caching in nextjs getServerSideProps() for optimized performance

I am currently developing an application using nextjs that retrieves data from a firebase firestore. The issue I am facing is that the application makes these requests on every page load, even when the data does not need to be completely up to date. To add ...