How can you effectively combine JavaScript objects using the "join" method?

I'm currently using MeteorJS in conjunction with MongoDB.

Within my project, I am managing two collections:

  • events, which contains idEvent
  • eventsType, which contains idEventType (a finite list of event types)

The relationship between the two collections is established by matching idEvent == idEventType.

The objective is to create an array of events, each associated with its corresponding event type object.

Although the following code works, I personally find it quite messy... What are your thoughts on this?

  events() {
    // Retrieve event types
    const eventsType = EventsType.find();
    const eventsTypeArray = [];
    eventsType.forEach((ev) => {
      eventsTypeArray[ev.idEventType] = ev;
    });

    // Retrieve events
    const eventsList = Events.find();
    const eventsListArray = [];

    // Merge data from both collections
    eventsList.forEach((ev) => {
      const evObj = ev;
      evObj.type = eventsTypeArray[ev.idEvent];
      eventsListArray.push(evObj);
    });

    return eventsListArray;
  }

Thank you! :D

Answer №1

To enhance your eventsList, you can utilize the map function in conjunction with Object.assign :

eventsListArray = eventsList.map(ev => Object.assign({type: eventsTypeArray[ev.idEvent]}, ev))

Here's a test example :

originalArray = [{a:"1"}, {a:"2"}];
dataMap = { "1": 10, "2": 100 };
mappedArray = originalArray.map(i=>Object.assign({b:dataMap[i.a]}, i));
console.log(originalArray);
console.log(mappedArray);

The outcome would be :

[{a:"1"}, {a:"2"}] // The original array remains unchanged
[{a:"1", b:10}, {a:"2", b:100}] // mappedArray now contains the additional data

Answer №2

Recently, I encountered a similar issue where I needed to combine data from two different collections.

To tackle this problem, I opted to establish a new client-only collection, also known as a local collection.

In the client:

const MergedData = new Mongo.Collection(null);

Instead of simply pushing the combined objects into an array, I utilized the MergedData collection to store them. This approach allowed me to query the newly merged objects from the local minimongo collection. Remember to clear the local collection upon template or component destruction and set up a tracker function to empty the MergedData if the cursor changes.

Tracker.autorun((dataChange) => {
    MergedData.remove({});
});

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

A guide on transferring values from three separate arrays into a designated div using JavaScript

Imagine having 3 div elements and 3 different sets of arrays. The goal is to assign the values from each array into corresponding divs. How can this be achieved? Take a look at my sample divs below: <div id='001'><div id="nr001">< ...

What could be causing the creation of numerous connections in my database?

I'm currently working on a NextJs website that utilizes MongoDB as its database. The following code establishes the connection to the database and stores it in cache: import { MongoClient } from "mongodb"; let cache = {}; export default ...

The Node.js REST API encountered an issue with the message "Unable to submit /api/v1/product."

I'm currently working on setting up a post method for a REST API using Node.js. I'm encountering an issue where Postman is saying "cannot post /API/v1/product," but there are no errors showing up in the console. Can anyone provide assistance with ...

​Troubleshooting findOneAndUpdate in Next.js without using instances of the class - still no success

After successfully connecting to my MongoDB database and logging the confirmation, I attempted to use the updateUser function that incorporates findOneAndUpdate from Mongoose. Unfortunately, I ran into the following errors: Error: _models_user_model__WEBPA ...

Clearing outcomes upon Python code's culmination

At the moment, I am undertaking a project that requires me to store a variable number of images within the program's scope. Given that the quantity of images is not fixed and may consume all available space for my project. I am curious to learn if th ...

What is the best way to change the CSS of a particular element within the #shadow-root (open)?

Can you help me modify the display of the p element inside the SR element with the #one id using CSS? #one ?SHADOW-ROOT-QUERY-SELECTOR? p { display: none}; <div> <p>My Website</p> <div id="one"> <!--#shadow-root (o ...

Attempting to grasp the distinction in output between map and flatMap functions in the Swift programming language

When using flatMap let scoresByName = ["Henk": [0, 5, 8], "John": [2, 5, 8]] let flatMap = scoresByName.flatMap { $0.key } print(flatMap) The output is ["J", "o", "h", "n", "H", & ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

Sending an AJAX request from one subdomain to another subdomain within the same domain

Is it true that cross-domain ajax requests require a 'proxy' server to be used? But what if an ajax request is made from server1.example.com to server2.example within the same domain of example.com? Would that still not work? I've noticed ...

Node.js MongoDB Error: db.open is undefined

I recently started experimenting with MongoDB and encountered an error message stating TypeError: db.open is not a function. Although new mongodb.Server and new mongodb.Db seem to be functioning correctly. The issue arises while using [email protecte ...

What is the most efficient way to prevent duplicate items from being added to an array in a Vue 3 shopping cart

I currently have a functional shopping cart system, but I am facing an issue where it creates duplicates in the cart instead of incrementing the quantity. How can I modify it to only increment the item if it already exists in the cart? Also, I would like t ...

Delete an item without a guardian

This situation differs from the one discussed in Remove dom element without knowing its parent?, because their element has a parentNode. While I am familiar with removing an element through its parentNode, creating a new element poses a different challeng ...

Tips for finding a specific string within an array using PHP

Is there a way to extract a specific string from an array? Below is an example of the array: Array ( [0] => Paper:300gsm Silk [1] => Lamination:Gloss [2] => Despatch:Standard 5 day ) I am looking to find if Despatch exists in the a ...

When should CSS compression and combining / JS minification be performed - at runtime or during build time?

I need to find a way to compress, version (for caching reasons), and possibly combine our JS and CSS files. I've come across two main approaches so far: 1) During the build process: Using an MSBuild task or similar. 2) Dynamically at runtime: Through ...

Troubleshoot: Firebase deployment of Vue.js application unable to locate page

I'm currently working on a silly web app with my friends for some laughs. We're using Firebase hosting and Discord OAuth2. The issue arises when attempting to access the "/login" page either by entering it in the URL or clicking "authorize" on th ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...

Encountering difficulties when attempting to log with the Serilog MongoDb sink

Our development MongoDB server is hosted on AWS. I have successfully been able to insert data using the Mongo Shell and C# driver. However, I am facing issues when trying to do the same using the Serilog MongoDB sink. Here is the code that works using dir ...

Is it possible to execute an npm package without using the npm run command?

Is there a way to initiate the next.js build process directly through the command line without needing to use the package.json file? Can we execute it without relying on npm run? Perhaps running next build in the command line could achieve this instead of ...

The function FormatCurrency is non-existent

I need assistance with converting a textbox value into a currency using the jquery.formatCurrency-1.4.0.js plugin. My JavaScript function is set up like this: $(document).ready(function() { $('.currency').blur(function() { $(&apo ...

Creating a JavaScript and C# popup for deleting records in asp.net

I'm struggling a bit with understanding how server-side deletion works. I know how to use MessageBox, but it's not the best approach. I've been advised to use a popup on the server side. What I'm trying to achieve is that when you clic ...