Using pipes to filter JSON data based on key value pairs

I have a collection of items in the specified structure:

{
            img: './app/images/codeeval.png',
            title: 'CodeEval',
            repository: 'https://github.com/Shooshte/CodeEval',
            description: 'Solutions to CodeEval challenges written in JavaScript and shared on GitHub.',
            github: true,
            demo: false,
            completed: true
        }

Currently, I am working on creating a custom filter that takes a string input, checks if the object has that particular property set as true, and then returns all objects meeting this condition. For instance, if I provide the string 'demo', it should display all objects where demo: true.

Here's my HTML code snippet:

<div *ngFor="#item of items | itemFilter: 'demo'" class="portfolioItemContainer">
    <img [attr.src]="item.img" class="portfolioImage">
    <h2>{{ item.title }}</h2>
    <a [attr.href]="item.repository">
        <div>
            <p>{{ item.description }}</p>
        </div>
        <p class="portfolioLinkToRepo">View Code!</p>
    </a>
</div>

This is how my component looks like:

import { Component } from 'angular2/core';
import { ViewEncapsulation } from 'angular2/core';
import { Pipe, PipeTransform } from 'angular2/core';

@Component({
    selector: 'portfolio',
    templateUrl: '/app/views/portfolio.html',
    styleUrls: ['../app/styles/PortfolioMobile.css', '../app/styles/PortfolioOther.css'],
    pipes: [itemFilter],
    encapsulation: ViewEncapsulation.None
})

export class PortfolioComponent {
    items = [{
        img: './app/images/placeholder.png',
        title: 'veryNiceWords',
        repository: 'https://github.com/Shooshte/veryNiceWords',
        description: 'An app created for posting, rating, and sharing quotes over social networks. Still a work in progress.',
        github: true,
        demo: false,
        completed: false
    },
        // Additional items omitted for brevity
    ];
}

@Pipe({ name: 'itemFilter' })
class itemFilter implements PipeTransform {
    transform(items: Array, [key]): string {
        return items.hasOwnProperty(key);
    }
}

In the console, I'm encountering the following error message:

angular2.dev.js:23730 EXCEPTION: Error: Uncaught (in promise): Unexpected piped value 'undefined' on the View of component 'PortfolioComponent'

If anyone could assist me in identifying what I might be doing incorrectly, I would greatly appreciate it.

Thank you for your assistance

Answer №1

Classes do not support hoisting. It's important to define your pipe before your class definition:

@Pipe({ name: 'pagesFilter' })
class pagesFilter implements PipeTransform {
  transform(pages: Array, [key]): string {
    return pages.hasOwnProperty(key);
  }
}

@Component({
  selector: 'portfolio',
  templateUrl: '/app/views/portfolio.html',
  styleUrls: ['../app/styles/PortfolioMobile.css', '../app/styles/PortfolioOther.css'],
  pipes: [pagesFilter],
  encapsulation: ViewEncapsulation.None
})
export class PortfolioComponent {
  (...)
}

Note: Update

Your pipe function should return an array instead of a boolean value:

@Pipe({ name: 'pagesFilter' })
class pagesFilter implements PipeTransform {
  transform(pages: Array, [key]): string {
    return pages.filter(page => {
      return page.hasOwnProperty(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

What are some methods of creating an infinite category JSON listing?

I am struggling to create an unlimited JSON loop based on the parent_id category. Despite my efforts in searching for a solution, I have been unable to find a suitable source. Can someone help me understand how to implement a foreach loop efficiently? Your ...

Discovering the way to retrieve information from a service in Angular post-subscription

This is the service I provide: getDataDetails(id: any) { this.dataDocumment = this.afs.doc('data/' + id); return this.data = this.dataDocumment.valueChanges().subscribe(res =>{ this.data = res; console.log(this.data); ...

Having trouble adding new elements to my JSON array using Python

This particular line seems to be causing the issue at hand data["Objects"]["Text"].append({"f":"var6", "g":"var7", "h":"var8"}) Here is the function in its entirety def CreateTextJSON(TextObject): print("s") with open('base.json') as f ...

Tips for updating a session cookie in nestjs

After successfully setting up session authentication using NestJS, I have always relied on JWT and set a short expiration time for access tokens. In order to obtain a new access token, the frontend must refresh it. Now, I am facing the challenge of implem ...

Angular2 Final: Issue with inline template - incorrect format for number pipes

Problem <h2>{{totalTargetValue | currency:'EUR':true:'2'}}</h2> Issue Error while using inline template: the specified digit info for number pipes is invalid. Do you have any suggestions on how to resolve this error? ...

What could be the root cause behind the error encountered while trying to authenticate a JWT?

I've been working on integrating a Google OAuth login feature. Once the user successfully logs in with their Google account, a JWT token is sent to this endpoint on my Express server, where it is then decoded using jsonwebtoken: app.post('/login/ ...

What is the best way to divide percentages accurately in Angular?

I am currently working on splitting percentages dynamically with Angular. For example, if txtBox1 has 75%, I want to split the remaining 25% between txt2 and txt3. If I change txt1 to 50%, then I want txt2 and txt3 each to receive 25%. The values may vary, ...

I encountered a UnicodeEncodeError stating "'ascii' codec cannot encode characters at positions 9-14: ordinal not within range(128)."

I recently received this troublesome code from a questionable API in Python 3.5: b'{"code":67,"message":"\xe7\xa7\x81\xe9\x92\xa5\xe9\xaa\x8c\xe8\xaf\x81\xe5\xa4\xb1\xe8&b ...

What is the best method to extract specific data blocks from a JSON array in SwiftUI?

Although I am new to SwiftUI and haven't written any code yet, I have a JSON file with nested data that I want to extract and display on a simple view. Is there an easy method in SwiftUI for extracting specific blocks of data from a JSON file? Any gui ...

I am experiencing some difficulty with the GetServerDate using the JSON protocol in JQuery; it's

I am facing an issue while trying to execute a basic ajax call to fetch data from a file on a server. Even though I can access the file via the web browser and have diligently followed tutorials related to this topic, I have hit a dead end. Here is the sn ...

Is it feasible to add a row in bold font following every set of 10 rows written in regular text?

Looking for a way to implement pagination on a table with dynamic headers? I am using rows with font-weight:bold to act as headers for the pagination. Is it possible to insert a row with font-weight:bold every 10 rows? I am unsure of how to achieve this, ...

The use of the || operator within arguments

I am facing a challenge: //this console log displays correct value console.log('localstorage', localStorage.getItem('subMenu')); setSubMenu( JSON.parse(localStorage.getItem('subMenu') || JSON.stringify(s ...

Encountering the error "No overload matches this call" while utilizing useQuery in TypeScript may indicate a mismatch in function parameters

My issue lies with TypeScript and types. Here is the API I am working with: export const clientAPI ={ //... getOptions: async (myParam: number) => get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) =& ...

Problem encountered when attempting to retrieve information from a web service in Angular 4

I am currently attempting to retrieve data from a web service API. However, all I can see is the data on the console. The web service requires an ID, so I input the ID first and then proceed to obtain the data related to that ID within the web service us ...

A guide on implementing a "Select All" trigger in mat-select with Angular8/Material

Here is the code I have created: <mat-form-field appearance="outline"> <mat-label>Handler Type</mat-label> <mat-select multiple [(value)]="handlerType"> <mat-option *ngFor="let handler of handlerT ...

Transforming TypeScript snapshot data in Firebase Cloud Functions into a string format for notification purposes

I've encountered the following code for cloud functions, which is intended to send a notification to the user upon the creation of a new follower. However, I'm facing an issue regarding converting the snap into a string in order to address the er ...

Access the JSON data stored in the File Directory by reading and utilizing it for your project

Can someone help me figure out how to retrieve data from the xmltojson.json file and assign it to a variable using JavaScript? const jsonfile = require('jsonfile') const file = 'xmltojson.json' jsonfile.readFile(file, function (err, obj ...

Modify the size of the fabricjs text box to perfectly match the chosen text

I'm currently facing an issue with my code snippet that is supposed to create a new Textbox: new fabric.Textbox('Add some text') The problem I'm encountering is that the text box appears too small compared to its content: https://i.s ...

The clash of dependencies in Transloco

Currently, I am in the process of integrating the Transloco package into my Angular Ionic project that I compile using VSCode. My Angular version is 13.3.0. Upon executing the installation command: ng add @ngneat/transloco I encounter a series of terminal ...

Error: Unable to locate module: Cannot find module './' in 'C:pathToFeeds'

Despite the numerous times this question has been asked before, none of the answers seem to apply to my specific situation. The issue I am encountering in my application is highlighted in the title: Below is the layout of my app's directory: https: ...