Angular: rendering JSON data as a dynamic grid

I'm looking to organize and display user scores by date in a matrix format where each user has only one score per date.

My desired matrix layout is as follows:

Date         User1   User2   User3
2020-01-05   40      20      20
2020-01-03   40      30      -
2019-12-02    -      23      -

I have fetched the data from an API in the form of a JSON array consisting of objects with date, user, and score details. Is it possible to present this data in the format of the matrix mentioned above?

I attempted using *ngFor with various nesting options but couldn't achieve the desired outcome. Should I restructure the data before attempting to display it?

Here's an example of the JSON data:

{ 
   "results":[ 
      { 
         "date":"2020-01-05",
         "user":"user1",
         "score":40
      },
      { 
         "date":"2020-01-05",
         "user":"user2",
         "score":20
      },
      { 
         "date":"2020-01-05",
         "user":"user3",
         "score":20
      },
      { 
         "date":"2020-01-03",
         "user":"user1",
         "score":40
      },
      { 
         "date":"2020-01-03",
         "user":"user2",
         "score":30
      },
      { 
         "date":"2019-12-02",
         "user":"user2",
         "score":23
      }
   ]
}

Answer №1

The script provided below generates a matrix as per your requirement:

const data = {
    "results": [
        {
            "date": "2021-05-10",
            "user": "john_doe",
            "score": 70
        }
        ...
    ]
};

const users = Array.from(new Set(data.results.map(i => i.user)));
const dates = Array.from(new Set(data.results.map(i => i.date)));

const resultMatrix = [
    ['Date', ...users],    // Header row
    ...dates.map(date => { // Additional rows
        return [
            date,          // Date column
            ...users.map(user => { // Values columns
                const userScore = data.results.find(i => i.user === user && i.date === date);
                return userScore ? userScore.score : '-';
            })
        ];
    })
];

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

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

Rearrange list items by dragging and dropping

Here is the HTML and TypeScript code I have implemented for dragging and dropping list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop List in Green Area: </h4> <ul class="unstyle"> <l ...

Utilize Optional Chaining for verifying null or undefined values

I have utilized the following code: data?.response[0]?.Transaction[0]?.UID; In this scenario, the Transaction key is not present, resulting in the error message: ERROR TypeError: Cannot read properties of undefined (reading '0') Instead of chec ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

Exploring the capabilities of @angular/cli and integrating it with non-angular scripts can significantly

After upgrading my application to Angular 5, I decided to experiment with @angular/cli instead of using different webpack configs from the Angular starter package like I did previously. Our build process is fairly simple except for one aspect that I' ...

Error encountered on Firefox browser when saving content in TinyMCE editor: NS_ERROR_UNEXPECTED

We are currently experiencing an issue on the Firefox browser where our component with the tiny-mce editor displays an NS_ERROR_UNEXPECTED message and does not show any content upon reloading. Initially, when the editor loads for the first time, the conte ...

Using Angular's FormControl with a Pipe

Trying to manipulate the value of an <input> using a pipe and display the modified value in a <paragraph> has proven to be quite challenging. Despite various attempts and thorough research, I have not been able to achieve the desired functional ...

In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together. HTML CODE : <input type="tex ...

Differences between Angular services and exportsIn Angular,

I have a collection of straightforward tool functions that do not require sharing state across the application, do not need to be singleton instances, and do not rely on injected services. Is there any benefit to using an injectable service like: @Inject ...

A guide on integrating mat-select into Angular input fields

I've been trying to implement a mat-select dropdown on my input field, but for some reason, when I click on the arrow, nothing happens and the list doesn't show up. Usually, with autocomplete, when a user starts typing, all the options are displ ...

Angular failing to render data in user interface

Exploring the concept of CRUD Operations, I am attempting to implement basic CRUD operations using Angular for the front end and Web API for the back end. The API is quite straightforward, returning a simple JSON structure as shown below: [ { "stud ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

The typescript error "Cannot read properties of undefined" is encountered while trying to access the 'map' function

I was attempting to follow a guide on creating an app using typescript and react, but I'm encountering an error that says "Cannot read properties of undefined (reading 'map')". I'm not sure why this is happening, can someone please offe ...

Utilizing getter and setter functions within a setter with a type guard

I need to implement a getter and setter in my class. The setter should accept a querySelector, while the getter is expected to return a new type called pageSections. The challenge I'm facing is that both the getter and setter must have the same argum ...

Angular modules are designed to repeat chunks of code in a

Whenever I scroll the page, my function pushes items to an array. However, I am facing an issue where the pushed items are repeating instead of adding new ones. Solution Attempt onScroll(): void { console.log('scrolled'); var i,j,newA ...

Navigating with Angular: Displaying child components on separate pages

When I click on a button in match-controls.component.html, I want my child component (BasicStatControlComponent) to load on a new page. However, the component is rendering directly below the buttons instead. How can I fix this issue? Any help would be appr ...

Unexpected expression after upgrading to TypeScript 3.7.2 was encountered, file expected.ts(1109)

After updating TypeScript from version 3.6.x to 3.7.2, I started using optional chaining in my code. However, I encountered a peculiar error. Error message: Expression expected.ts(1109) This error appeared in both my (vim, VSCode) IDE, even though the ...

Loading Angular 4 Material Tabs when a tab is selected

Can lazy loading be implemented with Angular Material Tabs? If not, I am looking for a solution to execute a method when switching tabs. ...

Is it possible for an Interface's property to be a type that contains an array?

As I dive into the Angular code, I encountered a peculiar type for a property within an Interface named 'Origin' that has left me perplexed. Here's the snippet: export interface Origin { areaNum?: number; open?: { [key: stri ...

Tips for configuring the _document.tsx file in Next.js for optimal performance

I found most of the code for this project in the official documentation example on utilizing styled-components: https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.js However, the example was written in .js and I ...