Exploring the Angular TypeScript Method for Rendering Nested Objects in an Array

Within this array, I have a collection of objects that contain properties for model and color. My goal is to present these objects in a table format, with individual access to the color values.

grp = [ {model: "CF650-3C", color: {Orange: 3, Black: 2} }, {model: "HD4533F", color: {Black: 2, Orange: 1} } ]

I've attempted to iterate over the array and display them in a table:

<table class="table table-striped" >
<thead>
  <tr  >
    <th scope="col">Model</th>
    <th scope="col">color</th>
  </tr>
</thead>
<tbody>
  <ng-container *ngFor="let g of grp">
  <tr >
   
    <td>{{ g.model }}</td>
    <td>{{ g.color | json }}</td>

  </tr>
</ng-container>
</tbody>

The output currently displays both models with their respective color values as JSON objects. However, I am struggling to individually access the keys and values within the colors object.

CF650-3C    { "Orange": 3, "Black": 2 } 
HD4533F     { "Black": 2, "Orange": 1 } 

Answer №1

Here are some techniques you can implement:

Try using the keyvalue pipe to iterate through object values keyvalue pipe

  <ng-container *ngFor="let g of grp">
  <tr >
    <td>
     <div *ngFor="let c of g.color | keyvalue">
      Key: <b>{{c.key}}</b> and Value: <b>{{c.value}}</b>
     </div>
    </td>
    <td>{{ g.model }}</td>
  </tr>
 </ng-container>

You can create a component and assign your object as an @input StackBlitz

  <ng-container *ngFor="let g of grp">
  <tr >
    <td>
     <app-color [Color]="g.color"></app-color>
    </td>
    <td>{{ g.model }}</td>
  </tr>
 </ng-container>

If needed, you can also develop a custom pipe that will return specific values based on your object UltimateCourses

  <ng-container *ngFor="let g of grp">
  <tr >       
    <td>{{ g.model }}</td>
    <td>{{ g.color | mycolorpipe }}</td>    
  </tr>
</ng-container>

Answer №2

Here's a way to achieve it:

<ng-template *ngFor="let item of items">
  <tr>
    <td>{{ item.name }}</td>
    <td>{{ Object.keys(item.properties) }}</td>
    <td>{{ Object.values(item.properties) }}</td>
  </tr>
</ng-template>

Answer №3

To access each color in the object, you will need to loop through using the ngFor directive. *ngFor="let color of game.colors"

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

What is the best way to automatically check dynamic checkboxes in Angular reactive forms based on database values?

As a beginner in reactive forms, I am facing challenges with dynamically setting the value of checkboxes to true. For instance, when retrieving pre-selected fruit values for a specific user from the database, I want those fruits to be checked when the page ...

Error message indicating a problem with global typings in Angular 2 when using Webpack is displayed

My project is utilizing angular 2 with webpack and during the setup process, I encountered Duplicate identifier errors when running the webpack watcher: ERROR in [default] /angular/typings/globals/node/index.d.ts:370:8 Duplicate identifier 'unescape& ...

Discovering a way to retrieve objects from an array of objects with matching IDs

Here is a code snippet I put together to illustrate my objective. arr = [ { id:1 , name:'a', title: 'qmummbw' }, { id:2 , name:'b', title: 'sdmus' }, { id:2 , name:'', title: 'dvfv' }, ...

Encountering a issue while running npm start with Angular 2 RC build

After upgrading from Angular2 beta 15 to the RC version, I encountered some errors while trying to run my application. typings/browser/ambient/es6-shim/index.d.ts(8,14): error TS2300: Duplicate identifier 'PropertyKey'. typings/browser/ambient/e ...

Mapping the preselected values of multiple input fields into an array in Angular 6: A step-by-step guide

When submitting a form with input fields, I need to capture the selected values into an array format like {"userid":1,"newstatus":[1],"mygroup":[1,2,3]}. I attempted using ngmodel but encountered issues. Below is the code snippet: home.component.html & ...

The NodeJS backend is receiving an empty request body from the Ionic frontend application

In my Ionic app (Angular2) with a Node backend, I have implemented a feature called Level, where each Level has its own title. Users can view a list of levels and add new ones through a modal. However, I encountered an issue where the titles are not being ...

What is the process for moving information between files?

I have two files which are named as, employee-rates-controller.ts: private load() { return this.entityService .load(this.$scope.projectRevisionUid) .then(resp => { localStorage.removeItem('employeerates'); this.$ ...

The value 'var(--header-position)' cannot be assigned to type 'Position or undefined'

Description of Issue I am attempting to utilize a CSS Custom Property to customize a component within a nextjs application using TypeScript. Strangely, all CSS properties accept the CSS variables except for the position property which triggers the error b ...

Having trouble with CSS Locator identifying an element in your Protractor Test?

In the Protractor test snippet below, I am attempting to calculate the quantity of div elements using the CSS locator: let list = element.all(by.css('div[class="ag-header-cell ag-header-cell-sortable"]')); expect(list.count()).toBe(11); ...

How can you specify the active route in Angular?

I am curious about whether it is possible to set the active route from a script instead of just from the HTML template. Let me provide an example: @Component({ template: `<input type="button" (click)="back()" value="back" ...

convert all the characters to lowercase in JSON

I have a JSON file containing information about classes and annotations like this- {"classes":["BUSINESS","PLACE","HOLD","ROAD","SUB","SUPER","EA","DIS","SUB&quo ...

Creating robust unit tests for Node.js applications with the help of redis-mock

I am facing an issue while trying to establish a connection with redis and save the data in redis using the redis-mock library in node-typescript, resulting in my test failing. Below is the code snippet for the redis connection: let client: RedisClientTyp ...

Styling <Link> component with styled-components: A step-by-step guide

Utilizing the Link component from @material-ui/core/Link in my TypeScript code was initially successful: <Link href="#" variant="body2"> Forgot? </Link> However, I am exploring the transition to styled-components located in a separate file. ...

Experimenting with Date Object in Jest using Typescript and i18next

I have included a localization library and within my component, there is a date object defined like this: getDate = () => { const { t } = this.props; return new Date().toLocaleString(t('locale.name'), { weekday: "long", ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

I am facing a problem with the code for my React login page and router

My form page is built in react and typescript, utilizing JWT tokens on the API side. While there are no issues with the container page, I encountered an error on the index.tsx page where the routers are defined: A TypeScript error occurred in C:/Users/yusu ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

How to properly integrate Bootstrap with Angular 2?

Currently developing an angular2 app and contemplating whether to include bootstrap reference on the component level or in the index.html file. Interested to learn about the advantages and disadvantages of each approach. Thank you! ...

Tips for preventing a wrapped union type from collapsing

It seems like there is an issue with Typescript collapsing a wrapped union type when it knows the initial value, which is not what I want. I'm uncertain if this is a bug or intended behavior, so I'm curious if there's a way to work around it ...

Steps for eliminating a selection in the dropdown list:

I am dealing with a situation in which my select element gets new options added based on a specific input value. However, each time the value is changed, more options are appended to the select element instead of replacing the old ones. How can I remove th ...