Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below:

export class DtoTransactionCategory {
    categoryName: String;
    totalPrice: number;
}

Using groupBy function:

import { groupBy} from 'lodash';

  let result = groupBy(transactionCategoryList, (c: DtoTransactionCategory) => {
      return c.categoryName
    });

Result:

https://i.stack.imgur.com/KHvST.png

To further manipulate the array and calculate the total price for each category, I need my data to be structured as follows:

let myNewArry = [{categoryName:"cat1",totalPrice: 9400},
                    {categoryName:"cat2",totalPrice: 600}]

Could you please guide me on achieving this final step using Lodash modules?

Answer №1

let data = {
category1: [{totalPrice: 2}, {totalPrice: 3}],
category2: [{totalPrice: 2}, {totalPrice: 5}]
}
const totalPrices = _.map(data, (value, key) => ({name: key, totalPrice: _.sumBy(value, 'totalPrice')}))

console.log(totalPrices)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

Tips for Removing Padding in Material UI Container Component

I'm currently working on creating a hero banner using the material-ui framework and I've encountered an issue. Here's what I have so far: https://i.stack.imgur.com/UXTDY.png However, I'm facing an irritating problem with left and rig ...

Using the max-width property with Semantic UI Dropdown in ReactJS

I'm struggling to determine how to adjust the max-width of the Dropdown element in ReactJS. I attempted the following: .Menu Dropdown { max-width: 5rem !important; } Unfortunately, this did not work as expected. The dropdowns are taking up too m ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...

I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

"Enhancing user experience through file uploads using the onchange event

I'm currently working on implementing file upload functionality using the onchange event. I encountered an error stating that 'file is not defined.' //html file <input type="file" style="display: none;" onchange="angular.element(th ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...

Gradually appear/disappear div element with a delay added

Storing divs in an array and deleting them after appending is my current method. Now, I'm looking to incorporate a fade-in and fade-out effect on each div with a delay. Check out this code snippet : var arr = $(".notification"); function display ...

Is it possible to calculate a variable within a dataset using existing data as a reference point?

Is there a way to dynamically compute some of the data variables in a Vue instance by referencing other variables and tracking their changes? new Vue({ el: '#root', data: { x: 1, y: x + 1 } }) <script src="https://cdnjs.cloudf ...

The requested `GLIBC_2.28' version required by node cannot be located, leading to an inability to amplify the version

While there were numerous questions about this topic, I am specifically seeking solutions for amplify. Below are the logs from my amplify build: 2024-01-14T16:14:17.626Z [INFO]: # Cloning repository: <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Tips for retrieving the present value of a piped/converted BehaviorSubject

How do I retrieve the current value of the observable generated by readValue() below without subscribing to it? var subject = new BehaviorSubject<Object>({}); observe(): Observable<Object> { return subject.pipe(map(mappingfunction)); } Do ...

Adjusting a Vue Slider with a changing value

Currently, I am utilizing the Vue Slider component from this source. My goal is to enhance the functionality of the slider by increasing it to the next index and beyond. The issue lies in the fact that the current implementation increments by 1, as the val ...

A Guide to Accessing Numbered Properties within an Object

I am working with a large Object that has over 700 properties, all numbered. How can I efficiently iterate through each of these numbered properties? { '0': { emails: { categorized: [Object], all: [Object], primary: &a ...

In my Express Javascript application, I recently encountered a challenge where I needed to export a const outside of another

I am currently working with a file named signupResponse.js const foundRegisterUser = function(err, foundUser){ if(!err){ console.log("No errors encountered") if(!foundUser){ if(req.body.password == req.body. ...

Model with no collection involved

Take a look at this Model and View setup. Why is the indicated line not functioning as expected? var app = app || {}; (function () { app.CurrentUserView = Backbone.View.extend({ el: $('.avatar-container'), template: ux.templ ...

Dynamic placeholder modification depending on form selection

How can I dynamically change the placeholder text based on user selection? //div with a toggle for two options <div fd-form-item> <label fd-form-label for="select-targetType">Showroom type:</label> <select class=&q ...

React code is displaying as plain text and the components are not being rendered properly

My latest creation is a component named "componentRepeater" with the main purpose of displaying multiple instances of child components. The props within the "componentRepeater" include properties for the child components, the number of repeats for the chil ...

Typescript interface created specifically for React Higher Order Component Props

Consider the React HOC provided below which adds sorting state to a component: import React, {Component, ComponentClass, ComponentType} from 'react' interface WithSortState { sortOrder: string } interface WithSortInjectedProps { sortO ...

Converting a React Typescript project to Javascript ES5: A step-by-step guide

I have a react typescript project and I need to convert the source code (NOT THE BUILD) to ES3 or ES5 JavaScript. This is because I want to use this code as a component in another React app. Can you suggest which preset and plugins I should use for this t ...

Image not showing up when using drawImage() from canvas rendering context 2D

Need help with drawImage() method in JavaScript <head> </head> <body> <script type = "text/javascript"> var body, canvas, img, cxt; body = document.getElementsByTagName("body" ...