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

Preventing the compilation process from overwriting process.env variables in webpack: A step-by-step guide

Scenario I am currently working on developing AWS Lambda functions and compiling the code using webpack. After reading various articles, I have come to know that the process.env variables get automatically replaced during compilation. While this feature ...

Encountering an issue while attempting to access a JSON file using the fetch method

When attempting to read a json file locally, I encountered an error that looks like this: Fetch API cannot load file:///var/www/desktop-electron//dashboard/bnb.json. URL scheme "file" is not supported Below is the code snippet being used: fetch(`${drr}/ ...

Encountering a problem with TypeScript while employing Promise.allSettled

My current code snippet: const neuroResponses = await Promise.allSettled(neuroRequests); const ret = neuroResponses.filter(response => response?.value?.data?.result[0]?.generated_text?.length > 0).map(({ value }) => value.data.result[0]?.genera ...

Exploring the power of query parameters in Ionic 4

Currently, I am in the process of transitioning a web-based Ionic 3 project to Ionic 4. Upon scanning a QR code, a page is supposed to open with a URL structure like this: domain.com/qanda/pwa/home?user=simon&skill=ionic&role=Admin&Table=132 ...

Transforming the Server-side model to the Client-side model within Angular 4

My Server-side C# model public class Instructor:Entity { public string Name { get; set; } public string PhoneNo { get; set; } } Client-side TypeScript model export class Instructor extends Entity { public name:string; public address ...

Facing an issue with the TypeScript error in the Tailwind-Styled-Component Npm package. Any suggestions on how to troub

module.styles.ts File import tw from "tailwind-styled-components"; export const Wrapper = tw.div` bg-green-500 `; export const Link = tw.a` text-blue-500 `; home.jsx File import React from "react"; import { Wrapper, Link } from &qu ...

Upon launching Google Chrome, a series of errors plague the WSL2 Ubuntu setup while running Karma and Jasmine for Angular testing

My Angular project utilizes Google Chrome for testing with Karma & Jasmine, but upon starting Chrome, I encounter multiple errors. Despite trying various solutions found on Stack Overflow, none have been successful. The versions in use are: Chrome 99.0.4 ...

In Python, extract data from the top level of a JSON file

Looking for assistance with parsing a JSON stored as a string: message = """{"info":{"keyVersion":1,"timestamp":"2020-11-05 20:00:00","encryptedData":"75657374696f6e732068617665207265636 ...

The NG8002 error has occurred, as it is not possible to connect to 'matDatepicker' because it is not a recognized attribute of 'input'

I've come across an issue while working on my Angular 15 application with Angular Material. I'm trying to incorporate a date picker, but after adding the code snippet below, I encountered an error. <mat-form-field appearance="outline" ...

Does the XML format of a resource representation offer more stability against causing disruptions than JSON within a REST API?

When using XML in the data representation of your REST api instead of JSON, will it facilitate modifying the data representation without causing issues for the client? For instance, if we currently include a first name and last name in the data but then d ...

How to generate a JSON object in a Bash script by capturing the output of a command

As I delve into a shell script, my primary goal is to dynamically transform the output of a command into a JSON object. The structure of the output seems favorable, formatted as "key":"value". In theory, this should be straightforward, right? However, afte ...

Unable to provide any input while utilizing npm prompts

After installing npm prompts, I encountered a strange issue. When trying to run the example code for npm prompts, I found that I couldn't enter any input at all. The underscore in the input field would blink for a few seconds, then the cursor would ju ...

Angular/TypeScript restricts object literals to declaring properties that are known and defined

I received an error message: Type '{ quantity: number; }' is not assignable to type 'Partial<EditOrderConfirmModalComponent>'. Object literal may only specify known properties, and 'quantity' does not exist in type &ap ...

Switching between two distinct templateUrls within an Angular 6 component

When working with Angular 6, we are faced with having two different templates (.html) for each component, and the need to change them based on the deployment environment. We are currently exploring the best practices for accomplishing this task. Some pos ...

Accelerating Angular DOM Generation

I have encountered a challenge while building a large menu using an extensive JSON object. Initially, with around 250 nodes, the performance was acceptable and I considered the project completed. However, the scope has now expanded to require over 3,000 no ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

Tips for waiting for an observable loop

When using my application, the process involves uploading a series of images in order to retrieve the file IDs from the system. Once these IDs are obtained, the object can then be uploaded. async uploadFiles(token: string):Promise<number[]> { let ...

Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects: let data = [{ createdDate: "2222", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>", histories: [ ...

Having trouble setting a default value for your Angular dropdown? Looking for alternative solutions that actually work?

Objective: Customize the default value for a dropdown menu to switch between English (/en/) and Spanish (/es/) addresses on the website. Challenge: Despite extensive research, including consulting various sources like Angular 2 Dropdown Options Default Va ...

Error in Laravel due to incorrect UTF-8 character encoding is causing issues

When attempting to retrieve a list of all directories and include that list in a JSON response, an error is encountered indicating that the response contains malformed UTF-8 characters. The presence of letters such as "Æ Ø Å" in the directories is causi ...