Exploring Angular 5's *ngFor directive with an array of objects

Here is the data I am working with:

Initial set of data:

var input = [
    {ru: "R201", area: "211", unit: "211"},
    {ru: "R201", area: "212", unit: "NONE"},
    {ru: "R201", area: "HCC", unit: "NONE"}];

Desired result data:

var result = [
    {area: ["211", "212", "HCC"],
    ru: "R201",
    unit: ["211", "NONE"]}];

I am encountering an issue while trying to loop through this data in a template using ngFor. The error message states that it cannot find a differ supporting object 'R201' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

This is the function I have written:

  this.groupBy = _
  .chain(input)
  .groupBy('ru')
  .map(function(value, key) {
      return {
          ru: key,
          area: _.uniq(_.pluck(value, 'area')),
          unit: _.uniq(_.pluck(value, 'unit'))
      }
  })
  .value();

And here is the corresponding template code:

<ion-list no-lines class="menus">
  <ion-item ion-item *ngFor="let p of groupBy; let i=index" (click)="toggleLevel1('idx'+i)" [ngClass]="{active: isLevel1Shown('idx'+1)}">
    <ion-row>
      <ion-col col-9>
        <span ion-text>
          <strong>{{ p.ru }}</strong>
          <ion-icon [name]="isLevel1Shown('idx'+i) ? 'arrow-dropdown' : 'arrow-dropright'" float-right></ion-icon>
        </span>

        <ion-list no-lines *ngIf="isLevel1Shown('idx'+i)">
          <ion-item no-border *ngFor="let menu of p.ru; let i2=index" text-wrap (click)="toggleLevel2('idx'+i+'idx'+i2)" [ngClass]="{active: isLevel2Shown('idx'+i+'idx'+i2)}"><br>
            <span ion-text>
              <strong>&nbsp;{{ menu.area }}</strong>
              <ion-icon [name]="isLevel2Shown('idx'+i+'idx'+i2) ? 'arrow-dropdown' : 'arrow-dropright'" float-right></ion-icon>
            </span>

            <ion-list no-lines *ngIf="isLevel2Shown('idx'+i+'idx'+i2)">
              <ion-item no-border text-wrap><br>
                <span ion-text (click)="openEquipmentPage(p.dataRu,menu.area,menu.unit)">
                  &nbsp;{{ menu.unit }}
                </span>
              </ion-item>
            </ion-list>
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
  </ion-item>
</ion-list>

I would appreciate any help or guidance on resolving this issue. Thank you in advance!

Answer №1

You have the power to modify your outcome based on this information.

let data = .chain(input)
  .groupBy('ru')
  .map(function(value, key) {
    return {
      ru: key,
      area: _.uniq(_.pluck(value, 'area')),
      unit: _.uniq(_.pluck(value, 'unit'))
    }
  }).value();

this.groupDataBy = [];

for(let key in data){
  groupDataBy.push({key: key, values:data[key]});
}

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

Unable to retrieve npm repository from GitHub

I've been grappling for approximately 2 hours to integrate a repository into my angular project without success. Here's the link I've been trying: https://github.com/cmelange/ECL-3D-Components#ecl-3d-components. Despite previously having i ...

Looking to extract nested JSON data and display it in a PHP table with two separate tables arranged similarly to the JSON structure?

From my PHP file, I am trying to retrieve data from a JSON file and display it in tabular form using PHP. However, I'm encountering an error while attempting to retrieve values from the expense table in the JSON file. The specific error message I am ...

I'm looking for a way to send a value to my component when the onBlur event is triggered on a PrimeNG autocomplete textbox. Any

I'm currently utilizing the PrimeNG autocomplete textbox. How can I pass a value to my component on the onBlur event? Template <p-autoComplete (ngModelChange)="orguser.userid = $target.value" class="ui-autocomplete autocomplete" [suggestions]="r ...

When using *ngFor with AngularFireList, an error is thrown indicating an invalid

I'm struggling to grasp why I'm getting an invalid pipe argument error with *ngFor when using async. Without async, I'm told that NgFor only supports binding to iterables like Arrays. Oddly enough, the same code works fine on another page bu ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Exploring the concept of nested dictionaries in web development: how to utilize

Here is a snippet of my JavaScript code: var emotions = {}; $('#emotions').children('#emotionFields').each(function(){ emotions[$(this).find($('.emotion')).val()]=$(this).find($('.value')).val() }); $ ...

Transformed an object into a DataTable

When working with a JSON response, the structure may look like this: { "cod": "OK", "list": [ { "date": "31\/10\/2018", "count": "109", "name": "PAUL" }, { "date": "30\/09\/2018", "count": "103", "name": "LUKE" } ]} ...

Issue with accessing data from database in my app

I am currently working on a project that involves retrieving data from my database. The user inputs a car registration number and a rating (ranging from 1 to 5) and then clicks a button. Upon clicking the button, my code is supposed to execute, fetching te ...

Tips on harnessing the power of CreateReducer within the ActionReducerMap<State> entity?

I'm trying to use the CreateReducer method to create a reducer, but I'm running into issues and not sure why it's not working. I attempted to modify the State class, but that doesn't seem to be the right approach. export const reducer ...

Angular 2 project experiencing issues with implementing Bootstrap styles

After adding Bootstrap CSS to angular-cli.json - styles, I noticed that the styles were not being applied to my project. I also added it in package.json and did an npm install. Can anyone suggest a solution? Here is a snippet from angular-cli.json: ...

Have you noticed the issue with Angular's logical OR when using it in the option attribute? It seems that when [(ngModel)] is applied within a select element, the [selected] attribute is unable to change

Within the select element, I have an option set up like this: <option [selected]=" impulse === 10 || isTraining " value="10">10</option> My assumption was that when any value is assigned to impulse and isTraining is set to true, the current o ...

Tips on preventing state sharing in Angular applications

Delving into the world of Angular has presented me with an intriguing issue. I've crafted a component dedicated to displaying a dialog, complete with its own template (HTML), CSS, and TypeScript files. Whenever a user clicks on an item within a list ...

Retrieve data from submit button in Angular and use it as a parameter to invoke a function

I am working on a HTML file that includes a dropdown list: <select> <option *ngFor="let t of items" value="t"> {{ t }} </option> </select> In addition to the dropdown list, there ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Incoming information obtained via Websocket

Currently, I am working with Angular and attempting to retrieve data from the server using websockets. Despite successfully receiving the data from the server, I am faced with a challenge where instead of waiting for the server to send the data, it retur ...

Issue filtering information ExtNet and Json

Hi everyone, I am new to asp.net and Ext.net and I am looking to create some dynamic interfaces. However, I am facing a challenge. I am using Ext.Net along with a web service that returns JSON objects. The issue arises when it comes to paging - I only re ...

What is the best method to extract information from JSON files that begin with a curly brace "{ "?

I am utilizing the themovieDB API to parse a JSON. The JSON begins with { so it lacks any root or if it does have one, I am unsure how to reference it in Swift. When I attempt to parse it with a root that I created, it throws this error: "keyNotFoun ...

What is the best way to perform unit testing on a function component that includes React.useState() using jest and enzyme?

I'm working on a function component that utilizes React.useState() to handle the state of a drawer modal. My challenge lies in testing this function and its ability to modify state using jest enzyme, as I cannot access its state function due to it not ...

During the transpiling process, the metadata of an Angular component may become lost

Encountering another error: Uncaught Error: Unexpected value 'UserDialogComponent' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Current behavior Summary: When incorporating an external libra ...

Is your TypeScript spread functionality not functioning as expected?

I'm new to TypeScript, so please forgive me if I've made an error. On a guide about TypeScript that I found online, it states that the following TypeScript code is valid: function foo(x, y, z) { } var args = [0, 1, 2]; foo(...args); However, w ...