Why does mapping only give me the last item when I try to map onto an object?

Why does mapping onto an object only give me the last item? Below is the object displayed in the console:

0: {Transport: 2}

1: {Implementation: 9}

2: {Management: 3}

When I use ngFor, it only provides the last item

const obj = this.assigned_group;
// refined collection
const result = Object.values(
  obj.reduce((c, v) => {
    c[v] = c[v] || [v, 0];
    c[v][1]++;
    return c;
  }, {})
).map((o) => ({ [o[0]]: o[1] }));

this.assigned_group_delta = result.map((a) => {
  this.x = a;
});
console.log(this.x);

// The output only shows the last item in the object

Answer №1

Continuously updating this.x is the cause for its final value.

Hence, it retains the value of the last item.

Answer №2

The solution I discovered utilizes the following technique:

calculateItemCount(item: any) {
  const itemCounts = {};
  const itemList = item;
  itemList.forEach(function (element) { itemCounts[element] = (itemCounts[element] || 0) + 1; });
  return itemCounts;
} 

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

Incorporate matTooltip dynamically into text for targeted keywords

I'm currently tackling a challenge in my personal Angular project that utilizes Angular Material. I'm struggling to find a solution for the following issue: For instance, I have a lengthy text passage like this: When you take the Dodge action, ...

Is it possible to utilize ngIf to reuse a component when encountering a 404 error? How can the error be captured?

In my app-routin.module.ts file, I have a root component named HomeComponent that I reuse for unknown routes. const routes: Routes = [ { path: '', component: PrimaryComponent, data: { breadcrumb: 'PRIMARY'}, children: [ { p ...

Is there another option for addressing this issue - A function that does not declare a type of 'void' or 'any' must have a return value?

When using Observable to retrieve data from Http endpoints, I encountered an error message stating that "A function whose declared type is neither 'void' nor 'any' must return a value." The issue arises when I add a return statement in ...

A Model in TypeScript

{ "title": { "de-DE": "German", "fr-FR": "French", "en-CA": "English" }, "image": "/tile.jpg", "url": "/url/to/version" } After receiving this JSON data, my model structure is as follows: export class MyModelStruct ...

What is the best way to ensure a specific row remains at the bottom of an Angular table with Material when sorting?

My data table contains a list of items with a row at the end showing the totals. | name | value1 | value2 | --------------------------- | Emily | 3 | 5 | | Finn | 4 | 6 | | Grace | 1 | 3 | | TOTAL | 8 | 14 | I&apos ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...

Using an asynchronous for loop to assign a background image to a div element

I am facing an issue with setting the background image of an observable array in my Ionic application. Here is the code snippet I am using: <ion-card *ngFor="let picture of pictures$ | async;" <div class="user-image" [ngStyle]="{'background- ...

Restricting the selection of only one checkbox in an Ionic4 application

Currently working on enabling only one checkbox in my Ionic 4 app. I've made some progress with the code but now I'm stuck. I believe I need to implement ngModel for this task. The goal is to set response.checked to true when a checkbox is checke ...

Issue with Angular2: Child components are not sending events to parent components

There are two components, one nested within the other. A click function in the child component triggers an event emitter that emits a string. In the parent template, the event emitter is used to call a function in the parent component that logs a simple me ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

The URL "http://localhost:8100" has been restricted by the CORS policy, as it lacks the necessary 'Access-Control-Allow-Origin' header on the requested resource

`The CORS policy has blocked access to the XMLHttpRequest at 'http://localhost/phpfile/leave-option.php' from the origin 'http://localhost:8100'. This is due to the absence of the 'Access-Control-Allow-Origin' header on the re ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

Strategies for splitting a component's general properties and accurately typing the outcomes

I am attempting to break down a custom type into its individual components: type CustomType<T extends React.ElementType> = React.ComponentPropsWithoutRef<T> & { aBunchOfProps: string; } The code appears as follows: const partitionProps = ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

The formatting directive fails to keep pace with speedy input

I am working on a feature to automatically format the input field as the user types, transforming the letters into valid initials in uppercase with dots in between. The formatting needs to happen in real-time as the user inputs characters, rather than aft ...

Using C# to generate a JSON array by extracting information from a CSV file

I am trying to generate JSON data in C# by pulling information from a CSV file. The desired JSON structure is shown below: { "car":[ { "manufacturer": "Nissan", "fuelType": "p ...

Paths: Integrate a variety of components along with essential information

With 3 components in hand, everything works smoothly when I run them on AppComponent: <app-sections #appSection></app-sections> <app-form #mainForm [section]="appSection.currentSection"></app-form> <app-match [bestMatchHTMLEleme ...

A Guide to Iterating Through Arrays of Objects Using TypeScript

Currently, I am engrossed in an Angular project where I am fetching an object containing an array of objects from an API. The object being passed to the API as a parameter through my service is called "reportData". Here is an example of the data retrieve ...