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

Revitalizing Ionic 2 Chart.js Graphic

I'm currently facing an issue with updating a doughnut chart when navigating back to a component. The chart is not refreshing as expected. renderChart(oplTitle, oplScore, oplScoreDifference) { this.options = { type: 'doughnut', data: { ...

Having difficulty with utilizing struct pointers effectively in C

I am currently in the early stages of learning C and facing challenges with using structs within functions. Despite passing a pointer to my struct to the functions and attempting to modify their values, it seems that the functions are unable to alter the v ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Make sure to send individual requests in Angular instead of sending them all at once

I am looking to adjust this function so that it sends these two file ids in separate requests: return this.upload(myForm).pipe( take(1), switchMap(res => { body.user.profilePic = res.data.profilePic; body.user.coverPic = res.data.coverPic; ...

Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have: Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" } This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular. Now, I want to populate this data into the following ...

Safari experiencing hang after successful CORS OPTIONS request

Safari (10 - OSX El Capitan) Issue with CORS Encountering a problem with CORS while performing a POST request from an AngularJS front-end to a Laravel back-end. In Chrome and Firefox, both OPTIONS and POST requests return http status 200 OK In Safari 10 ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Set the parameter as optional when the type is null or undefined

I need to create a function that can take a route and an optional set of parameters, replacing placeholders in the route with the given params. The parameters should match the placeholders in the route, and if there are no placeholders, the params should b ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Prevent the element attribute from being enabled before the onclick function is triggered

I am attempting to implement a feature in Angular that prevents double clicking on buttons using directives. Below is the pertinent code snippet from my template: <button (click)="onClickFunction()" appPreventDoubleClick>Add</button> And her ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

add array to a specific field in SQL database

Currently working with the codeigniter framework, I have an array that I would like to insert into a database with columns named sibbling_name and sibbling_age. I followed a tutorial in CodeIgniter, but encountered an error because the fields in the datab ...

What is the best way to utilize numpy in order to generate an array that calculates the total of values from a csv document, where the initial column consists of strings and the subsequent columns consist of

Looking to calculate the total power supply per hour for each plant in a CSV file using NumPy while maintaining dimensions. Below is a sample of the data: PLANT 1.00hrs 2.00hrs ... 22.00hrs 23.00hrs 24.00hrs AFAM IV - V 30.0 30.0 ... 50 ...

Record the variable as star symbols in the VSTS Extension

I am working on a VSTS extension using Typescript and utilizing the vsts-task-lib Currently, I am encountering an issue with the execSync function, which displays the command being executed. However, I need to hide a token obtained from a service by displ ...

Discover the best practices for implementing services within the import decorator of an angular module configuration

Is there a way to access a service inside the load module in Angular, especially when the module is loaded from a decorator and the service is not yet DI? You can refer to this answer for an example. For instance, if the method in the service returns an ...

I keep seeing "Uncaught TypeError: Unable to retrieve property 'get' from undefined" error message popping up

Currently, I am attempting to retrieve a JSON from a separate microservice (local) utilizing a different port. There is uncertainty as to whether the issue lies within my configuration or the microservice itself. Despite successfully displaying the JSON on ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

Retrieve the object property based on an array of indices

I am looking to create a function that can retrieve a specific property of an object based on an array of property names const getObjectProperty = (arr: string[], object: any) { // This function should return the desired object property } Expected Outco ...

What is the best way to change specific elements in an array to 0?

I have come across numerous instances where individuals substitute specific elements in an array with zeroes based on their values. For instance: X = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20] Setting all values < 4 to zero is not what I am looking ...