Difficulty arises when attempting to add multiple properties simultaneously in TS/JS through the use of map, set, and get functions

Struggling to create a summary of an array of objects grouped by one property value and summing 2 or more properties.

Unfortunately, my current approach only provides 2 values: the grouped-by property and the first summed property.

I can't seem to figure out how to sum the next property as well.

The initial array I'm working with is called

combinedItems

[
  {
    itemSi: 1,
    productId: 'one',
    taxableValue: 100,
    taxValue: 10,
    product: { id: 'one', productName: 'product one', taxId: 'one' },
    tax: { id: 'one', taxName: 'tax one' }
  },
  {
    itemSi: 2,
    productId: 'two',
    taxableValue: 100,
    taxValue: 10,
    product: { id: 'two', productName: 'product two', taxId: 'one' },
    tax: { id: 'one', taxName: 'tax one' }
  }
]

The goal is to group by taxName and calculate the total of taxableValue and taxValue.

const summaryValues = new Map<any []>();

 for(const {tax, taxableValue, taxValue} of combinedItems)
 

   summaryValues.set(
       tax.taxName,
       (summaryValues.get(tax.taxName) || 0) + taxableValue,
       (summaryValues.get(tax.taxName) || 0) + taxValue,
);

const summaries = [...summaryValues]
 console.log(summaries);
 
 const taxSummary = summaries.map(x => ({ 
  taxName: x[0], 
  taxableValue: x[1],
  taxValue: x[2]
}));

console.log(taxSummary)

The output I'm currently receiving is:

[ [ 'tax one', 200 ] ]

[ { taxName: 'tax one', taxableValue: 200, taxValue: undefined } ]

This is how the combined items are collected:

const items: any[] = [
    {
        itemSi: 1,
        productId: "one",
        taxableValue: 100,
        taxValue: 10
    },
    {
        itemSi: 2,
        productId: "two",
        taxableValue: 100,
        taxValue: 10
    }
    ];
    
const products: any[] = [
    {
        id: "one",
        productName:"product one",
        taxId: "one"
    },
    {
        id: "two",
        productName:"product two",
        taxId: "one"
    }
    ]
    
const taxes: any[] = [
    {
        id: "one",
        taxName:"tax one"
    },
    {
        id: "two",
        taxName:"tax two"
    }
    ]
    
    let combinedItems: any [] = [] 
    
    combinedItems = items.map(x => {
        let pdtItem = products.find(z => z.id === x.productId);


    let taxItem = taxes.find(z => z.id === pdtItem.taxId);
    
          let item = {...x, product: {...pdtItem }, tax: {...taxItem}};
          return item;
        });

console.log(combinedItems)

Answer №1

In the world of programming, a Map functions as a key-value store. It seems like you are attempting to use set with three arguments, but it actually only requires two - a key and a value.

If your goal is to generate multiple aggregations, one approach could be to save the results in an object:

const summaries = new Map();

for (const { tax: { taxName }, taxableValue, taxValue } of combinedItems) {
  const currentSummary = summaries.get(taxName) || { taxableValue: 0, taxValue: 0 }
  summaries.set(
    taxName, 
    { taxableValue: currentSummary.taxableValue + taxableValue, taxValue: currentSummary.taxValue + taxValue }
  );
}

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

Randomly position a div within a grid

I am currently working on creating a grid that spans 100% of the width of the browser window. Firstly, I am unsure about how to approach this grid creation, and secondly, I would like to have a div randomly positioned within the grid, filling the space onl ...

What function does the ng-template serve when encapsulated within an ng-select component?

Upon observing various instances of ng-select, I've noticed that it often involves wrapping a ng-template, as exemplified below: <ng-select [items]="cities" [(ngModel)]="selectedCity" bindLabel="name" bindV ...

Creating a never-ending scroll feature on a static page in Next.js

I am in the process of creating a portfolio using Next.js and have a large number of projects on the page. I would like to implement a feature where images start loading only when they enter the current viewport. This functionality works well with the defa ...

JavaScript loop to process form submissions

Running a for loop through data retrieved from the Facebook API, my goal is to store this data in my own database for use on other websites. The issue arises during the submission process, as it seems I can only submit once. The culprit appears to be the ...

When I try to execute a mutation with Apollo and React, I encounter a 400 error. It could be due to a

Every time I try to perform a mutation, I keep getting a 400 error code for some strange reason. Here is my httpLink code snippet: // ApolloProvider.js const httpLink = createHttpLink({ uri: 'http://localhost:3000/graphql', }); const client ...

Issue with passing Redux store to the component props

Struggling with my journey in learning Redux and React. I've set up the store, passed it to the <Provider> using react-redux, but all I see is an empty object when checking the console. import { createStore, applyMiddleware } from 'redux&a ...

Comparison between Static and Dynamic SVG

I have noticed a significant contrast in the rendering of static versus dynamic SVG. Take a look at this code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=devi ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Navigating Form Submission in Next.js

In this code snippet, I attempted to perform simple addition (ket=name + names). The desired outcome is a numerical sum displayed as “ket”. However, when entering 3 and 6 into the input fields, the result appears as 36 instead of 9. export default fu ...

Having trouble displaying dropdown in Angular 2 with PrimeNG

As I work on my app using PrimeNG and Angular2, I encountered a challenge with a component that is supposed to display a dropdown menu of selectable themes. Despite following the guidelines in the PrimeNG Dropdown documentation closely, I keep receiving an ...

Tips for Adding a Marker with Latitude and Longitude on a Three.js 3D Globe

Having some trouble with a basic 3D Globe in Three.js. Using Navigator to get the user's location and trying to place a marker on the globe representing the user's current position. However, I can't seem to get the marker at the correct posi ...

What is the method for determining the gaps between cells in a grid-based puzzle game similar to Sudoku?

this is my current code and it's successfully functioning var cellSize:Number = 36; var cellGap:Number = 4; var row:Number; var col:Number; for (var a:int = 0 ; a < puzzleSTR.length ; a++) { col = a % 9; row = Math.floor(a / 9); ...

Creating a new string by combining elements from an array using JavaScript

I need help creating a dot file from a string array. edges =[["Source1" ,"interfaceA" , "high" , "Sink1" , "interfaceB" , "high"], ["Source2" ,"interfaceC" , "hig ...

Switch color in Material-UI based on props

Utilizing code inspired by the Material-UI documentation on customizing the switch, you can customize the switch color to be blue: import React from 'react' import Switch from '@material-ui/core/Switch' import {withStyles} from '@ ...

My component in React is not getting rerendered despite changes in the state

Here's a straightforward scenario: index.tsx functions as the provider, while app.tsx serves as the consumer. Despite clicking the 'next' button and incrementing the questionNumber in the contexts, the QuestionDeserializer component fails to ...

Convert components into <input> using the "Edit" button, and store information with the "Save" button

My HTML script looks like this: <ul id="data"> <li>Value 1</li> <li>Value 2</li> <li>Value 3</li> <li>Value 4</li> </ul> <br> <div id="buttons"> ...

The use of window.Image() is ineffective when working with TypeScript and React

In my React project, I am utilizing the KonvaJS library. You can find more information about it here. To display an image using JavaScript/React, I have implemented the following code: componentDidMount() { const image = new window.Image(); ima ...

Is it possible to edit the JSON file served by the API in NextJS during runtime and have the API serve the updated file?

I apologize for the wording of my question. My main struggle lies in not being able to articulate it properly, as I have searched extensively online without finding a solution. In my usage of api routes in Next.js, I am seeking to serve a data.json file. ...

Animate items in a list by staggering their appearance during the initial rendering

I am currently working on creating a navigation menu that has a staggered effect when the list items appear upon opening the menu. Using a burger symbol to toggle the navigation menu to fullscreen, I want to incorporate an animation where each list item ( ...

How to store lengthy JSON strings in SAP ABAP as variables or literals without extensive formatting restrictions

Is there a way to input lengthy JSON data into ABAP as a string literal without the need for excessive line breaks or formatting? Perhaps enclosing the string in a specific template, or utilizing a method similar to JSON.stringify(..) found in other langua ...