Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours:

{
Name1: 9,
Name2: 10,
Name3: 30,
}

What changes can I make to my code to achieve a list of objects like this:

[{project: nameProj, hours: numProj}, {project: nameProj, hours: numProj},{project: nameProj, hours: numProj}]

This is my current code:


this.activities$
        .pipe(map((e) => e.map((e) => e)))
        .subscribe((e) => (this.dati = e));
      this.aggregated = this.dati.reduce((acc: DataTable[], activity) => {
        const projectName = `${activity.project?.customer.name} - ${activity.project?.name}`;

        acc[projectName] = (acc[projectName] ?? 0) + activity.hours;
        return acc
        });
      }, {});

Answer №1

Check out this solution for converting keys into an array:

let data = {
 Key1: 9,
 Key2: 10,
 Key3: 30,
}

let newArray = Object.keys(data).map(key => { return { item: key, value: data[key] } })

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

The value of type 'string' cannot be assigned to type '"menu" | "selectedMenu" | undefined' as it is not compatible with the specified types

I'm working on creating a multiple select feature using TypeScript, material-ui, and React. I am encountering an error when trying to set MenuProps.variant = 'menu'. The error message reads: "Type '{ variant: string; PaperProps: { styl ...

Tips for sending form data from ReactJS to controller in ASP.NET MVC:

Seeking help with React and ASP.NET integration. I am attempting to create a form in ASP.NET using React, but encountering issues when trying to pass form data from ReactJS to an MVC ASP.NET controller. Below is the code that I have been working on. Any su ...

Transferring Data in Vue.js Components through Props

I've encountered an issue while trying to pass a prop from the main Vue instance to a component. While one of the props is being successfully passed, the second one seems to be causing some trouble. Main Instance var app7 = new Vue({ el: &apos ...

Altering the dimensions of radio buttons

I am a newcomer to using material-ui. I am currently working on incorporating radio buttons in a component and would like to reduce its size. While inspecting it in Chrome, I was able to adjust the width of the svg icon (1em). However, I am unsure how to a ...

Tips for updating the DOM within a map function by utilizing the onChange event with a checkbox and react hooks

Initially, I imported a basic "database" object from another file that contains an array of students. I then used map to iterate through the student array and display all the students on the window object. Everything was working fine until I attempted to ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

Angular Material: Deleting an item when dropped outside a cdk component

Currently, I am utilizing Angular Material CDK DragAndDrop for specific list functionalities. My goal is to achieve the following: I want to be able to drag an element from List A and drop it into List B. Furthermore, if I drag an element from List B ...

JQuery selector is successfully working while vanilla JavaScript is not functioning as expected

This problem is unique because I am experiencing issues with querySelector and querySelectorAll in my JavaScript code. While JQuery works fine, vanilla JS does not work as expected. I would appreciate any insights on why this might be happening. Thank you ...

A simple way to add a value from a select option into a textarea when there are several dropdown menus and select elements sharing the same

I have several divs with the same class names where I need to input a value from a dropdown menu into the textarea that belongs to the div where the select element is located. I want this function to work smoothly even with more than 10 divs, which is why ...

What is the best way to accurately determine an element's location after scrolling to it?

I'm currently working on pinpointing the location of a specific element on a webpage once it has been scrolled to using JavaScript. Queries: How can I precisely determine the position of an element post-scroll? What are some common errors or extra st ...

how to check if a string has white spaces in a react application

If the input string has white space, the alert will indicate unsuccessful. If the input string does not have any white space, the alert will be successful. import React from "react"; export default function DropDown() { let i = document.getEle ...

Angular 14 captures typed form data as `<any>` instead of the actual data types

On the latest version of Angular (version 14), I'm experiencing issues with strictly typed reactive forms that are not functioning as expected. The form initialization takes place within the ngOnInit using the injected FormBuilder. public form!: For ...

Angular/Karma Unit Test for HttpClient

During my research on unit testing, I came across some very useful examples. Most of the examples focus on unit testing functions that interact with Angular's HttpClient, and they usually look like this: it('should return an Observable<User[] ...

JavaScript: Remove duplicates and count the number of unique properties in an array

Arrays have always been a challenging aspect for me, so I would really appreciate any assistance. ...

Combining Typescript and React to create a conditional callback prop type depending on whether an optional prop is

In my react component, I have the option to pass an optional prop called isSingle (boolean) and a required prop called onSelect (callback). If the isSingle prop is used, I want the callback to have a different signature. type CustomProps<T> = { ...

How to target only the parent div that was clicked using jQuery, excluding any

I have attempted to solve this issue multiple times, trying everything I could find on Google and stack overflow without success. At times I am getting the span element and other times the div - what could be causing this inconsistency? $(".bind-key"). ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

I am faced with a challenge involving an asynchronous function and the best approach to executing it synchronously

I devised the following plan: // Primary Function to Follow // Capture necessary local data // Transform into required editable format // Iterate through user's local images // Append image names to converted d ...

Issue with Primeng table: row grouping width does not work properly when scrollable is enabled

Currently, I am implementing a Primeng table within an Angular project. Below is the code snippet showcasing how the table is being utilized: <p-table [value]="cars" dataKey="brand" [scrollable]="'true'" scrollHeight="400px"> <ng-te ...