Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine.

Here is an example of my JSON data:

"locations": [
        {
         "id": "ASS",
        "name": "test center",
        "city": "Staten Island",
        "zip": "10301",
        "state" : "texas"
        },
        {
            "id": "ASD",
        "name": "test center1",
        "city": "Staten Island",
        "zip": "10301",
        "state" : "Florida"
        },
        {
            "id": "AAY",
        "name": "test center2",
        "city": "Staten Island",
        "zip": "10301",
        "state" : "Florida"
        },
        {
            {
            "id": "ASD",
        "name": "test center1",
        "city": "Staten Island",
        "zip": "10301",
        "state" : "Florida"
        }
    ],

The goal is to display the data grouped by state:

texas   : <div>ASS</div>
florida : <div>ASD</div>
      <div>AAY</div>
      <div>ASD</div>

In the 'group.pipe.ts' file:

@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
   transform(value: Array<any>, field: string): Array<any> {
    console.log('test');
    const groupedObj = value.reduce((prev, cur)=> {
          if(!prev[cur[field]]) {
        prev[cur[field]] = [cur];
  } else {
    prev[cur[field]].push(cur);
  }
      return prev;
    }, {});
    return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] 
  }));

}

And in the 'location.component.ts' file:

import {GroupByPipe} from '../group.pipe';
@NgModule({
  declarations : [GroupByPipe]
 })

However, I encountered an error:

Unhandled Promise rejection: Template parse errors:

The pipe 'groupBy' could not be found ("  <div class="col-sm-12 left_otr">
            <div class="col-md-6 col-sm-6 left" *ngFor="let [ERROR ->]item 
 of pagedItems | groupBy : 'state'">

Any suggestions on how to resolve this issue?

Answer №1

Successfully implemented the code below by passing an array and field:

 transformData(values: Array<any>, fieldName: string): Array<any> {
const groupedObject = values.reduce((previous, current)=> {
  if(!previous[current[fieldName]]) {
    previous[current[fieldName]] = [current];
  } else {
    previous[current[fieldName]].push(current);
  }
  return previous;
}, {});
return Object.keys(groupedObject).map(key => ({ key, value: groupedObject[key] }));
  }

Avoided using pipes in this solution.

Also updated the HTML structure as shown below:

  <div *ngFor="let section of sections">

                    <h1>{{section.key}}</h1> 

                    <div *ngFor="let detail of section.value">
                         // Implement logic here.
</div

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

Create dynamic visual representations of JSON data structures automatically

Looking for a service where I can create diagrams easily. Check out this example: Hope you have a great day! Thank you! ...

What is the internal mechanism used by Angular for routing implementation?

My traditional belief about web browsers has been challenged by the behavior of Angular. I used to think that when a user enters a new URL, the browser would fetch a whole new page from the network and display it, replacing the old one. But with Angular, ...

Sharing information between Angular components

Having recently started using Angular, I'm facing an issue with passing an array to a different component that is not parent or child related. What I aim to achieve is: upon selecting rows from the first component table, a new view should open up disp ...

How to retrieve values/keys from a JSON object dynamically in JavaScript without relying on fixed key names

shoppingCart = { "Items": 3, "Item": { "iPhone 11 Pro": { "productId": 788, "url": "http://website.com/phone_iphone11pro.html", "price": 999.99 }, "Bose Noise Cancelling Headphones": { ...

Using JavaScript to transform JSON information into Excel format

I have tried various solutions to my problem, but none seem to fit my specific requirement. Let me walk you through what I have attempted. function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { //If JSONData is not an object then JSON.parse will ...

Why does FormGroup.Get() return null when there is a period in the name of the FormControl?

Issue: I am facing an issue with the formGroup I created using formbuilder. The problem arises when a control within the FormGroup contains a . in its name. When attempting to retrieve the formControl using the formGroup.get method, it returns null. Sampl ...

The error message "global.HermesInternal - Property 'HermesInternal' is not found in the type 'Global & typeof globalThis'" appeared

I ran the auto-generated code below: $ react-native init RepeatAloud App.tsx /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local * ...

Converting a String into a Type or Component in Angular: A Step-by-Step Guide

Is it feasible in Angular to convert a string into a specific type or component? For instance, if I have the string "ListComponent", could I dynamically add a ListComponent to the application without using mapping techniques? stringComponent = "ListComp ...

React with Typescript - cannot be expressed as a function

I am currently exploring ReactJS and Typescript. While trying to authenticate a user using the methods below, I encountered the following error message: Unhandled Rejection (TypeError): auth.authenticate is not a function onSubmit src/components/Login/ind ...

Encountering errors in Visual Studio when trying to work with node_modules directories that have a tsconfig

In my current project, there is a tsconfig.json file located in the root directory. Strangely, Visual Studio keeps throwing errors related to other instances of tsconfig.json found in different packages, as shown below: https://i.sstatic.net/T7Co2.png Ev ...

conceal the selected button upon moving to a different page

Whenever I click on the details button, it directs me to the details.html file. However, when navigating to another page, the details button still appears and I want to hide it in such cases. <button mat-button (click)="onSelectApp(app)"><mat-ic ...

What is the best way to preserve a web response in a file?

I am currently facing an issue with saving a JSON web response in a file. Although I am able to successfully create and save the file, the content of the web response is not being captured. The file only contains: [object Object] Below is my component cod ...

What is the best way to retrieve a JSON key in ReactJS?

I am currently facing a rendering issue. In my componentDidMount function, I am using axios to make a GET call and then updating the state with the received JSON data. The problem arises when I try to access the keys of the JSON in the render method becau ...

Using TypeScript with React: Step-by-step guide to creating a ref prop

I'm currently using Ionic with React (typescript) and working on creating my custom form builder. Within this process, I've created a form that requires a ref property for referencing purposes when in use. My challenge lies in defining a prop tha ...

The checkbox component is currently not displaying on the ngx-datatable

The following HTML code snippet demonstrates a sample layout. The operations are functioning correctly, however, the checkbox is not visible. <ngx-datatable style="width: 90%" class="material" [rows]="rows" ...

Utilizing multiple API calls to initiate JSON data and seamlessly integrate it across the entire system

I am currently developing a project that utilizes Vue.js and Laravel for implementation. The project is focused on academia and consists of units, lessons, and activities, all interrelated. Each unit contains multiple lessons, and each lesson contains mult ...

Show a notification pop-up when a observable encounters an error in an IONIC 3 app connected to an ASP.NET

Currently, I am in the process of developing an IONIC 3 application that consumes Asp.NET web API services. For authentication purposes, I have implemented Token based auth. When a user enters valid credentials, they receive a token which is then stored in ...

Retrieve a specified quantity of JSON data from an external API

Dealing with a recently received API from an external source: (please note: the data returned is extensive) I'm aware that I can retrieve this large object by using the following method: $.getJSON('https://www.saferproducts.gov/RestWebServices ...

Retrieve the value of a duplicated object key from a JSON and replace it with just one unique value

In my current project, I am faced with the challenge of extracting duplicate object keys' values from a JSON dataset and replacing them with only one value. My goal is to ultimately return these unique key-value pairs as an array. NOTE: This data has ...

Tips for preventing "timeout while waiting for third-party check iframe message" when using Keycloak and Angular

I'm in the process of securing an Angular application with a Keycloak server. I've followed several tutorials with similar instructions, but I encountered an issue that has me stuck: Timeout when waiting for 3rd party check iframe message. My ...