Utilize *ngFor in Angular 9 to showcase both the key and values of an array

JSON Data

{
 "cars":
{
  "12345": [1960, 1961, 1962],
  "4567": [2001, 2002]
}
}

HTML Template

<strong>Plate and Year</strong>
<div *ngFor="let car of cars">
{{car}}
</div>

This should be displayed as:

Plate and Year

12345- 1960, 1961, 1962.

4567- 2001, 2002.

Answer №1

By utilizing the data structure provided, you can accomplish this task with the help of the KeyValuePipe, along with nested *ngFor loops. The KeyValuePipe enables you to iterate through an object similar to using Object.entries, giving you access to both a key and a value property for each item. In this scenario, the value will be an array that can be iterated over using another *ngFor:

<strong>Plate and year</strong>
<div *ngFor="let list of lists">
  <div *ngFor="let car of list.cars | keyvalue">
    <div>{{car.key}} - <div *ngFor="let year of car.value">{{year}}</div>
    </div>
  </div>
</div>

An interactive example showcasing this approach is available.

I hope this explanation proves helpful!

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

Angular Material Dropdown with Multi-Column Support

I'm working on customizing the selection panel layout to display items in multiple columns. However, I'm facing an issue where the last item in each column appears off-center and split, causing overflow into the next column instead of a vertical ...

Issue with asmx Web Service causing failure to return JSON data when using FineUploader for file uploads

I acknowledge that there are numerous questions similar to mine regarding this issue, but none of them have provided a solution for me. I understand that web services inherently convert my objects into json as part of the framework. I manually set the requ ...

What's causing the IndentationError in my Python code?

import requests import json url='https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY' headers= {'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36&ap ...

Iterating through the outcome of JSONResponse() from Django using jQuery

I am trying to retrieve the results of an insert operation from my views.py file in JSON format. The view I have looks like this: added={} if request.method=='POST': #Post method initiated. try: for id in allergies: ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

Updating the data attribute of an object in HTML using Angular

I am trying to embed a PDF viewer inside a component. In order to dynamically update the PDF document within a sanitizer, I need to use an attribute with []. This works fine with images. <img src="assets/pic.jpg"/> <img [src]="'assets/pi ...

Can a React.tsx project be developed as a standalone application?

As a student, I have a question to ask. My school project involves creating a program that performs specific tasks related to boats. We are all most comfortable with React.tsx as the programming language, but we are unsure if it is possible to create a st ...

Typedi's constructor injection does not produce any defined output

I am utilizing typedi in a Node (express) project and I have encountered an issue related to injection within my service class. It seems that property injection works fine, but constructor injection does not. Here is an example where property injection wo ...

retrieve serialized data using jQuery in C# webforms

Is there a way to retrieve jQuery serialized data in C# webforms code behind? I have attempted the following: jQuery.ajax({ type: "POST", url: "book_de_acoes.aspx/salvarSimulacaoAutomatica", data: JSON.stringify({ form: ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

Typescript service wrapper class returning Axios HEAD request

I am attempting to retrieve the header response using a custom Axios HTTP service wrapper. axiosClass.ts import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"; class Http { private instance: AxiosInstance | null = n ...

Encountered a timeout error of 2000ms while running tests on an asynchronous function within a service

Here is the service I am working with: class MyService { myFunction(param){ return Observable.create(obs => { callsDBfunc(param, (err, res) => { if(err) obs.error(err); ...

Diverse Selection of Font Awesome Icons

In my React project with TypeScript, I have a header component that accepts an Icon name as prop and then renders it. I am trying to figure out the best way to ensure that the icon prop type matches one of the existing FontAwesome Icons. import { FontAwe ...

Is it possible to utilize BehaviourSubject across different modules in Angular?

I am looking to utilize the BehaviourSubject for sharing data between two components that belong to different modules. How can I achieve this goal? CurrenciesModule export class CurrenciesComponent implements OnInit { defaultCurrency: CurrencyModel; ...

What is the best way to extract a deeply nested json value from couchbase?

Is there a way to query deep nested json values from couchbase? I have several documents in my couchbase bucket and I need to retrieve records where the app version is greater than 3.2.1, less than 3.3.0, or equal to 3.4.1. How can I retrieve these specif ...

Unable to access JSON data from LocalStorage using jQuery

Currently, I am encountering an issue while attempting to save a JSON array in jQuery to localStorage for future use. Unexpectedly, whenever I make the attempt to save it, an error indicating that the object is not defined arises. Below is my present code: ...

The process of prioritizing specific elements at the top of an array when ordering

In my array, I want to prioritize specific items to always appear at the top. The API response looks like this: const itemInventorylocationTypes = [ { itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7', itemInvent ...

Ways to update a JSON object within an array of objects

I've got an array of objects // Extracted from the database $scope.users = [{"$id":"1","UserID":3,"Name":"A","Selected":false},{"$id":"2","UserID":4,"Name":"B","Selected":false},{"$id":"3","UserID":5,"Name":"C","Selected":false},{"$id":"4","UserID":6 ...

Using ADAL with ASP.NET MVC and Angular for Seamless Login Experience

Currently, we have an ASP.NET MVC application in place but are looking to incorporate Angular for new frontend functions and gradually transition the entire frontend to Angular. However, at this stage, we are facing a challenge where user logins are only b ...