A guide to showcasing grouped information in typescript with the help of *ngFor

Trying to showcase my TypeScript data in a grouped format like this:

Make: Audi
  Model - Year
   R8 - 2012
   RS5 - 2013
Make: Ford
  Model - Year
  Mustang - 2013   

The JSON data I am working with is structured as follows:

this.cars = [
  {
      'make': 'audi',
      'model': 'r8',
      'year': '2012'
  }, {
      'make': 'audi',
      'model': 'rs5',
      'year': '2013'
  }, {
      'make': 'ford',
      'model': 'mustang',
      'year': '2012'
  }, {
      'make': 'ford',
      'model': 'fusion',
      'year': '2015'
  }, {
      'make': 'kia',
      'model': 'optima',
      'year': '2012'
  },
];

I'm utilizing a function to group the data by "make" key, borrowed from this Stack Overflow link

groupBy(list: any, key: any) {

  const newGroup = [];
  list.forEach(item => {
      const newItem = Object.assign({}, item);
      delete newItem[key];
      newGroup[item[key]] = newGroup[item[key]] || [];
      newGroup[item[key]].push(newItem);
  });
  return newGroup;

}

In TypeScript, I've implemented the following logic:

this.vehicles = this.groupBy(this.cars, 'make');

However, in the view template, the data isn't displaying despite using this syntax:

<div class="row alert-success" *ngFor="let vehicle of vehicles">
       {{vehicle}}
 </div>

When checking the console log for `this.vehicles`, it outputs:

[audi: Array(2), ford: Array(2), kia: Array(1)]
audi: Array(2)
0: {model: "r8", year: "2012"}
1: {model: "rs5", year: "2013"}
length: 2
__proto__: Array(0)
ford: Array(2)
0: {model: "mustang", year: "2012"}
1: {model: "fusion", year: "2015"}
length: 2
__proto__: Array(0)
kia: Array(1)
0: {model: "optima", year: "2012"}
length: 1
__proto__: Array(0)
length: 0
__proto__: Array(0)

Answer №1

When working with a 2D array like "vehicles", it's necessary to loop twice for proper iteration:

<div class="row alert-success" *ngFor="let vehicles of vehiclesArray">
     <div *ngFor= "let vehicle of vehicles">
       {{vehicle.model}} {{vehicle.year}}
     </div>
</div>

Answer №2

Revamp your {{car}} with the following changes

{{car.model}} {{car.year}}

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

Displaying a Collection of Strings Using PHP and MySQL

I am facing a challenge when it comes to displaying a list of strings from a MySQL server using PHP. I would like the list to have the following format: Name 1 Name 2 Name 3 Name 4 Each name should be in a separate cell, but I'm unsure about how to ...

I'm confused by the concept that DsGetDomainControllerInfo returns a "Pointer to a pointer variable that receives an array." Can someone explain this to me in simpler terms?

My primary experience lies in C#, so I'm still adjusting to working with C++. Currently, I am attempting to utilize DsGetDomainControllerInfo to retrieve all domain controllers within the domain. You can find more information about this function call ...

Reading a 2D array from a text file using Java

Whenever I scan my 2D array text file, an exception error occurs if there is no number present in the first line. The structure of my text file is shown below: 0 8, 3, 5, 4, 1, 6, 9, 2, 7 2, 9, 6, 8, 5, 7, 4, 3, 1 4, 1, 7, 2, 9, 3, 6, 5, 8 5, 6, 9, 1, 3, ...

Do argc / argv have an impact on the presence of null bytes in arrays?

How come the code snippet below produces 1238À§Wˇ ("123" + random characters) as expected, but when replacing int main(int argc, char *argv[]) with int main(void), it outputs only 123? #include <stdio.h> int main(int argc, char *argv[]) { ...

Generating custom perspectives of multi-dimensional arrays

In the realm of C++, I am currently tackling the task of creating a function to calculate marginal PDFs (Probability Density Functions). Essentially, this involves working with multi-dimensional data (PDF) defined across a grid of various variables. The pr ...

Can you make a quick edit to the text?

Currently, I am collecting user information from an edit text field. While I have a listener that captures their input upon clicking submit, I would like to also retrieve the information if they click back or anywhere else: https://i.sstatic.net/VjgVx.png ...

Is there a way to divide an array into two separate arrays when one of the elements within is nil?

Currently, I am working with Ruby 2.4 and have a specific task at hand. I need to split an array into two parts: the first part containing either the letter "a" or "b", and the second part holding everything else. Here's the code snippet I have been u ...

Tips for synchronizing object updates between parent and child components in React applications

I have a dilemma with my 2 components: The parent component looks like this: @Component({ selector: 'parent', template: ` <child [obj]="obj"> </child> `, styleUrls: [''], }) export class ParentComponent impleme ...

"Ways to retrieve an array of dates within a specified range of date and time

I am working with date fields in my project { tripScheduleStartDate: '2018-12-05T18:30:00.000Z', tripScheduleEndDate: '2018-12-07T18:30:00.000Z', } Is there a way to generate a datetime array from the start date to the end date, lik ...

Deciding Between Utilizing Observables or Promises in Angular

Having delved into Observables after transitioning from a predominantly Promise-based application, I recognize their effectiveness in handling streams and event patterns. However, I can't help but feel that there are instances where using Observables ...

Determining the presence of an element within an array stored in an object using JavaScript

I am currently working with an object that contains an array of objects structured like this: { 0: [ { value:1} { value:2} { value:3} ] } My goal is to determine if a specific element is present inside the array ...

Navigating the Cursor in Angular 5: Techniques for Moving the Character Cursor with Keyboard Arrow Keys in Internet Explorer 11

Currently, I am working with Angular 5 and integrating it with Ag-Grid Enterprise Addition. The issue I'm facing is when using the IE11 browser, the cursor gets stuck and doesn't move to the next characters in the input box while using the keyboa ...

The value of a boolean remains unaffected after a function is executed following a button press

I am facing an issue with two angular components. One of them should only be displayed when a search button in the first component is clicked. However, my code is not working as expected and I have to manually change the boolean value "clicked" for it to w ...

The module '@angular/compiler-cli/ngcc' is missing and cannot be located while trying to run ng serve

Out of the blue, I started encountering this error. It seems to be related to a version issue with angular-cli, but I'm unable to pinpoint the exact problem. Any assistance would be greatly appreciated! npm i displays some warnings and one compiler e ...

What is the process for incorporating a manually created Angular package into a project as a node modules package?

Looking for help on integrating a custom-built package into an Angular project instead of the default one installed via npm. I attempted to replace the original package in node_modules with my custom build, but encountered issues. The specific package I& ...

Issues with form validation in Angular reactive forms are causing problems

I recently created a complex reactive form by following the guidelines from this source on how to handle validation in Angular 9. After posting my code in StackBlitz, I ended up with three links: EDITOR URL APP URL EMBED URL If these links are not worki ...

Encountering an issue while upgrading to Angular 10: Unable to interpret "tsconfig.json" as a valid JSON AST Object

I'm currently updating my Angular 9 app to Angular 10 and encountering this error: > Removing "Solution Style" TypeScript configuration file support. × Migration failed: Failed to parse "tsconfig.json" as JSON AST Object. PropertyNameExpected at l ...

Unable to access the value of the initial element in the array

In my PHP code, I have an array named $team that contains various information about a team. Here's how it looks: array(22) { ["league_name"]=> string(28) "1.súdánská liga 2020/2021" ["league_id"]=> string(6) & ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

Encountering Duplicate Key Error When Implementing Angular, MongoDB, and Express

While working on my service, I encountered a situation where I needed to add a size when a user wants to add a product to the cart. Despite not having the size data included in the product information initially, as the size field in the database was empty ...