Getting into particular fields of an embedded object array using a dynamic variable in Meteor: a step-by-step guide

Users have defined an array of strings with different combinations:

pickedStrings = ["A", "B", "G", "L", "Y"];

This can also be:

pickedStrings = ["A", "G"] or pickedStrings  = ["A", "L", "Y"]

or any other mix. More strings may be added in the future.

These strings help identify objects in a mongo document by looping through the array and querying the objects.

var pickedArray, fLen, pickedDataArray, i;

pickedArray = pickedStrings;
fLen = pickedStrings.length;
pickedDataArray = [];

for (i = 0; i < fLen; i++) {

var item = pickedArray[i];

var values = valueCollection.findOne({'_id': "myDoc"}, {fields: {[item]:1 , '_id':0}});
console.log(values);

pickedDataArray.push(values);

}

console.log(pickedDataArray);

The console.log(pickedDataArray); displays only the desired objects specified by, for instance, pickedStrings = ["A", "B"];:

[
     { A:
          { GP: 37.56,
            ES: 67.51,
            EV: 12.12,
            CR: 45.90,
            Data: [Object] 
           } 
      },
      { B:
          { GP: 7.62,
            ES: 7.51,
            EV: 22.82,
            CR: 75.40,
            Data: [Object] 
           } 
       } 
]

Now, the goal is to extract single fields like GP per object from the query (pickedDataArray) and store them in a new array. So, we need the output:

neededArray = [37.56, 7.62]

However, there are two issues that need to be addressed. Firstly, it's unclear how to filter or retrieve just one field from this embedded object array. Attempted solutions like:

var neededArray = pickedDataArray.map(a => a.A.GP);

have resulted in arrays with undefined values. Secondly, the identifiers "A" and "B" provided by users are dynamic variables. Is it necessary to loop again using var item = pickedArray[i]; ?

This process utilizes the Meteor framework with MongoDB.

Answer №1

The result you're looking for can be achieved with the following code snippet. The condition is that both pickedStrings and pickedDataArray need to have the same length and order, otherwise sorting would be necessary.

let desiredResult = [];

const requiredField = 'GP';
for (let index = 0; index < pickedStrings.length; index++) {
   desiredResult.push(pickedDataArray[index][pickedStrings[index]][requiredField]);
}
console.log(desiredResult);

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

Utilize two separate functions within the onchange event of a v-checkbox component in a Vue.js application

I am currently using Vue.js with Vuetify and Laravel. In one of my components, I have a dynamic datatable that fetches data from the database using axios. Within this datatable, there are v-checkboxes. Everything is functioning as expected, but now I want ...

Sleek transitions for navigating between cells in a data table

I am looking to implement a smooth animation for cell navigation. Check out what I currently have: http://jsfiddle.net/0ardb3u0/ When the mouse hovers over a cell, I want the full column and row of that cell to be selected and highlighted in blue. How ...

beforeunload event confirmation prompt

I am currently working with Laravel and Vue.js to create a multi-step wizard. Within this wizard, I have implemented the onbeforeunload event to prevent any unwanted actions by displaying a confirmation message. However, I am encountering an issue where th ...

Can I add the object to the DOM and hold off on executing any events until the next

Just came across this intriguing interview question (shown below). Could someone please provide an explanation of the question and then offer a solution? Develop a function that takes an object and adds it to the DOM, ensuring that events are stored unt ...

JavaScript and Ajax are functioning properly in Mozilla Firefox, however there seem to be some compatibility issues with Google Chrome

I have a form that serves the dual purpose of registration and login, and I am using JavaScript Ajax to submit it. While it works smoothly in Mozilla Firefox, it fails in Chrome and IE. The goal is to execute an AJAX and PHP script that checks the databa ...

obtain hyperlinks on a website

Is it possible to retrieve links from a web page without actually loading it? Essentially, I would like to allow a user to input a URL and then extract all the available links within that webpage. Do you know of any method for accomplishing this task? ...

JavaScript encountered a ReferenceError: 'a' has not been declared

One interesting feature of my slider is that it uses links like <a id="foo" class="oslide">Chineese Food</a> to navigate through the slides. To make this navigation function properly, I had to include a.href = "#"; in the link's click even ...

What is the method for executing a nested query in the Parse API?

Within the user object, there is a list of features: skills: {"piano:10", "singing:5", ....}; I am looking to filter users based on their 'piano' skills. How can I achieve this? It doesn't have to be an exact match but should follow the ru ...

Having difficulty making my directive function in Angular

I'm encountering an issue with my directive not working properly. I suspect that I may have registered it incorrectly, but I can't seem to figure out the mistake. Could it be related to the naming convention? Here's the code snippet in quest ...

Unable to locate mongos

After installing the MongoDB 2.6 Standard, I am eager to set up a shard cluster. However, I am experiencing difficulty locating the mongos in the bin-directory. Any advice on how to proceed? Looking forward to your suggestions! Best regards, Andre ...

What is the method for obtaining a matrix (board) from a function in C++?

Currently, I am in the process of developing a straightforward game that requires me to generate a board of dimensions specified by the player. Despite my attempts, I am facing challenges with a function I am trying to write to produce the matrix for the ...

Utilizing the code plugin in conjunction with Popcorn.js

I am currently exploring the world of Popcornjs and attempting to utilize the code plugin. However, I am facing some challenges in implementing it successfully. After following this example and managing to get the video to play, I found myself unable to e ...

Modifying modal content disrupts AJAX events

When using jquery-ujs for ajax requests with data-remote="true", I encounter an issue where the first request goes smoothly but subsequent ones break. It seems that when certain events like $('#modal').empty(), $('#modal').tex ...

How can we incorporate dynamic HTML elements into a React JS application?

My code seems to be having an issue. I'm working on a registration form and trying to include an error message if the passwords entered do not match. For some reason, I am unable to dynamically add a para tag to my HTML. Any insights on why this could ...

Having trouble with an endless GET request loop in NextJS 13 while utilizing the Next-Auth middleware. Experiencing difficulties fetching the RSC payload

UPDATE: The issue has been identified! It seems that the bug is caused by using the beta turbopack. I have reported this problem and we are awaiting a resolution. Query: I recently delved into a project in NextJS 13 with the new app directory setup. Afte ...

Angularjs - Repeatedly reloading identical images

Whenever I use ng-src in the <img> tag and change the ng-src by clicking next or previous buttons, the browser reloads the image even though it's already loaded. This results in a not-so-smooth experience as the image is downloaded again before ...

What exactly does ".default" signify in Angular, Typescript, or Javascript?

Could someone please clarify the significance of the ".default" in the code snippet below? I am interested in implementing this code in our project, but my understanding of the mentioned code fragment is uncertain. (I have modified my question to display ...

Is there a way to prevent form submission when validation fails in an AJAX callback?

I am currently working on submitting a form with validation using ajax. After the ajax response, if the input field is valid, the form should submit; otherwise, an error message should be displayed. Below is the HTML code: <form action="new-join.php" m ...

Exploring the Possibilities with NodeJS and Socket.IO

I've encountered an interesting issue with my use of NodeJS and Socket.io. The server receives data through ZeroMQ, which is working perfectly fine. However, when there are a large number of connected clients (over 100), it appears that there is a de ...

Having trouble navigating through multiple layers of nested array data in react js

I need help understanding how to efficiently map multiple nested arrays of data in a React component and then display them in a table. The table should present the following details from each collection: title, location, description, and keywords. Below ...