Control the information stored in a nested array

Having difficulty manipulating data stored in an array using JS.

Here's my current code snippet:

FuelReceipt.aggregate([
                {$match:{date:{$gte: new Date(fuelStart), $lte: new Date(fuelEnd)}}},
                {$group:{_id: '$truckNumber', 
                         comdataPurchase:{$sum: '$comdataPurchase'},
                         defTotal:{$sum: '$defTotal'}}}]).exec(function(err, data){
                    if(err){
                        console.log('Error Fetching Model');
                        console.log(err);
                    }
                    console.log(JSON.stringify(data, null));
                    fuelArray = data;
                    console.log(fuelArray);
                    fuelArray.forEach(function(_id){
                        console.log(fuelArray['comdataPurchase']);
                    });
                });

Struggling to access nested data within the array.

Goal is to manipulate the following output:

[
  { _id: 567130, comdataPurchase: 525.49, defTotal: 38.79249 },
  { _id: 567132, comdataPurchase: 1050.98, defTotal: 77.58498 }
]

Need to calculate the difference between comdataPurchase and defTotal for each entry.

Appreciate any help you can provide in advance.

Answer №1

Feeling pretty special right now, haha!

FuelReceipt.aggregate([
                {$match:{date:{$gte: new Date(fuelStart), $lte: new Date(fuelEnd)}}},
                {$group:{_id: '$truckNumber', 
                         comdataPurchase:{$sum: '$comdataPurchase'},
                         defTotal:{$sum: '$defTotal'}}}]).exec(function(err, data){
                    if(err){
                        console.log('Error Fetching Model');
                        console.log(err);
                    }
                    console.log(JSON.stringify(data, null));
                    fuelArray = data;
                    console.log(fuelArray);
                    fuelArray.forEach(function(data){
                        console.log(data.comdataPurchase-data.defTotal);
                    });
                });

Challenge successfully solved!

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

Searching for a specific index using the .indexOf() method in

My current code includes a for loop that determines the presence of a specific character in strings for (var i = 0; i < length; i++) { console.log(name[i].indexOf('z') >= 0); } The issue at hand is that my code halts after just one i ...

Tips for updating a specific portion of a component in react.js

import React,{useEffect} from 'react'; import CloudTables from '@cloudtables/react'; import { useState } from 'react'; function DataGridTable ({ input1Value, input2Value }) { return ( <div className="con ...

What is the best way to retrieve the ID of the input element using a jQuery object?

After submitting a form with checkboxes, I retrieve the jQuery object containing the checked input elements. var $form = $(e.currentTarget); var $inputs = $form.find("input.form-check-input:checked") Here is an example of how the inputs are stru ...

Creating an array in C++

I attempted to create an array using the following code: char a[]="abc"; cout<<a<<" "<<sizeof(a); The output was: abc 4 Later, I tried this: strcpy(a,"abcdefgh"); cout<<a<<" "<<sizeof(a); The output was: abc ...

What steps should I take to modify the API addresses within the React project build?

In my React project, I am looking for a method to dynamically change the API addresses after building it. Is there a way to accomplish this without using environment variables? I want to be able to modify the API address even after the build process is c ...

Troubleshooting issue: Dropdown menu malfunctioning after using replaceWith() and appendTo()

I could really use some assistance. Admittedly, my knowledge of php, js, jquery, and similar languages is limited. I am currently working on a small web application where users fill out a form with specific requests, the data is then stored in a database, ...

Variables in the $scope object in AngularJS

Within my $scope in angularJS, I am working with two types of variables. 1). $scope.name and $scope.title are linked to input boxes in the UI html code. 2). On the other hand, $scope.sum and $scope.difference are internally used within my JS code. I need ...

Encountering this issue when setting up the forgot password functionality or trying to submit a POST request using Postman

Below is the code snippet related to resetting a password: exports.forgotPassword = async function(req, res, next) { //Check if user exists const user = await User.findOne({ email: req.body.email }) if (!user) { return next(new App ...

Our JSON array property is not being parsed correctly by AngularJS

Upon receiving our GET request, the response is as follows: { "access_token": "pi7ID4bsZIC9yN ... 76gnblw", "token_type": "bearer", "expires_in": 1209599, "userName": "super0", "userRoles": "["member", "admin"]", ".issued": "Tue, ...

Utilizing only a fraction of my dataset, I created a barplot in D

My d3.js barplot is based on JSON data with 12 elements. The 'fpkm' value determines the bar height, but only half of the elements are showing up correctly. When I use the data callback function in d3, it only returns values for the first half o ...

EventEmitter asynchronous callback

Can you attach an asynchronous callback to an EventEmitter in TypeScript or JavaScript? someEmitter.on("anEvent", async () => console.log("hello")); If so, does using an async function guarantee that the function will run asynchronously? Also, what ar ...

Collecting data from popups, modals, and dialog windows through scraping

Can data be extracted from popups, modals, or dialog windows? For instance: I am looking to gather email addresses from users (suppliers) listed on the site, but the information is displayed in a popup window. How can I scrape all the emails from these p ...

Storing an array of objects with properties in a plist file for safekeeping

I have an array called bugs that contains different types of objects such as strings, UIImage, etc. These objects are sorted as shown below: Example: BugData *bug1 = [[BugData alloc]initWithTitle:@"Spider" rank:@"123" thumbImage:[UIImage imageNamed:@"1.j ...

"Step-by-step guide on implementing a click event within a CellRenderer in Angular's Ag-Grid

paste your code hereI'm currently working on implementing edit and delete buttons within the same column for each row using Angular ag-Grid. To visually represent these buttons, I am utilizing icons. While I have successfully displayed the edit and de ...

Implementing JavaScript templates to display images: A step-by-step guide

I am facing an issue with displaying images on my page. The data for name and address is showing up, but the image is not being displayed. Here is the snippet of my code: var JSONObject = [{ name: 'Nyonya', ...

Eliminate any duplicate objects using JavaScript

Is it possible to remove duplicated objects with the same id using methods other than lodash's _.uniqBy? The id value is always changing, so sometimes I need to remove the object with id:123, but other times it will be a different id. import _ from ...

Tips for improving the efficiency of your search feature

In my React class component, I have implemented a search function that works well most of the time but can become very slow on certain occasions. The search functionality is triggered by onChange when there is an input change. The state "bigData" that is b ...

Send Ajax Form using php without the use of document.ready function

I've encountered an issue with my PHP Ajax form submissions on my webpage. The code works perfectly for forms that are preloaded on the page, but I'm having trouble with dynamic forms that are called using other JavaScript functions. I'm loo ...

What is the best way to send parameters to a callback function in a jQuery $.getJSON method?

Currently, I am attempting to utilize jQuery to access a custom API using Ajax/$.getJSON. In my code, I am trying to send a specific value to the Ajax callback method, but I am encountering an issue where this value is not being properly passed and instea ...

Why does miniMongo fail to locate a single document when it is present in Meteor React's findOne query?

I'm encountering a strange issue while querying the document. It appears that the Meteor API has been updated for querying documents, yet the documentation remains the same. Displayed below is a sample document from the database: meteor:PRIMARY> ...