Troubleshooting a common issue with Angular custom pipe filters and tackling the undefined error

Within my Angular 10 project, I've implemented a table that organizes data by category and includes search boxes and dropdowns for filtering. To filter the data, I utilized a custom pipe filter type. While it generally functions correctly, there are instances where an error is encountered:

Component.html:57 ERROR TypeError: Cannot read properties of undefined (reading 'toString')

Although testing on Stackblitz shows no issues, this error persists locally. Despite troubleshooting, I haven't been able to pinpoint the exact cause. Any assistance in resolving this matter would be greatly appreciated. Thank you!

You can view my code on Stackblitz here:

https://stackblitz.com/edit/angular-ivy-qwvmys?file=src%2Fapp%2Fapp.component.ts

Below is my pipe.service.ts code:

import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
  name: "search"
})
export class SearchPipe implements PipeTransform {
  transform(list: any[], value: any[], key: any[]): any {
    value.forEach((name:any, index) => {
      if (name) {
        list = list.filter((item) => {
          return (item[key[index]]
            .toString()
            .toLowerCase()
            .indexOf(name.toString().toLowerCase()) !== -1)
        });
      }
    });
    return list;
  }
}

HTML code snippet:

<div class="row mx-0 list-filter mb-4 pl-1">
  // HTML code
</code></pre>

<p>TypeScript file excerpt:</p>
<pre><code>import { Component, VERSION } from '@angular/core';
import { SearchPipe } from './servicer.filter.pipe';
// TypeScript code snippet...

Answer №1

Updated with additional if statements to prevent errors. The issue might have been caused by passing the $event.

  ngOnInit() {
    this.filterServicerData()
    console.log(this.allServicer)
  }

  filterServicerData() {
    this.availableFilteredServicer = this.searchPipe.transform(this.allServicer, [this.clientCode, this.clientName, this.clientStatus], ['clientId', 'clientName', 'status']);
    console.log(this.allServicer);
  }
  transform(list: any[], value: any[], key: any[]): any {
    value.forEach((name:any, index) => {
      if (name && name !== undefined) {
        list = list.filter((item) => {
          return (item[key[index]]
            .toString()
            .toLowerCase()
            .indexOf(name.toString().toLowerCase()) !== -1)
        });
      }
    });
    return list;
  }

See a working demonstration here: https://stackblitz.com/edit/angular-ivy-mrd9tj?file=src%2Fapp%2Fapp.component.ts

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

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...

Angular Service worker mishandles http redirects (302)

In my current project, I am implementing Angular and Spring Boot technologies. When I build the project, Angular generates the service worker for me. The issue arises when I use an external service (auth2) and my backend redirects to the login page after ...

The React client is unable to establish a connection with the server socket

Recently diving into the world of socket-io and react, utilizing express for the backend. The socket.io-client version being used is 3.0.3, while the backend's socket-io package matches at 3.0.3 as well. Interestingly enough, the server handles connec ...

Having trouble retrieving the elements from the JSON array defined in EJS within the JavaScript script tags

<div> let arrayData='<%= myJsonArray %>' <!--myJsonArray is passed to this ejs file via the render function in index.js when rendering this ejs file --> </div> <script> let index=0; function getData(){ c ...

Can one select a radio button without corrupting the data in VUE?

How can I preselect a value for radio buttons created using Vue's List Rendering without having a dataset in the script? Below is the code snippet for a better understanding of my goal: SCRIPT: data() { return { formData: {} //formData st ...

The image fails to display when using THREE.js and Panolens.js

Trying to create a 360-degree environment with informational buttons using THREE.js and Panolens.JS However, I'm unable to resolve why the image is not appearing. Continuously encountering the error: Uncaught ReferenceError: process is not defined. ...

Notification box appearing on the homepage

I created a landing page featuring various products. Each product is accompanied by a description and price. When you click on a product, a "popup window" should appear displaying the picture and description. My concern is that if I have numerous product ...

Java HTML and JS parser available for free!

Is there a parser available that is compatible with AJAX and allows you to customize the method of connecting (I prefer to use my own method to connect to pages)? ...

It appears that the JavaScript global dynamic variable is undefined as it changes from function to function, suggesting it might be

I'm encountering an issue with the way these two functions interact when used in onclick calls of elements. Due to external circumstances beyond my control, I need to keep track of when and how elements are hidden. Everything works perfectly as inten ...

What is the best way to retain checkbox states after closing a modal?

I have a modal that includes multiple checkboxes, similar to a filter... When I check a checkbox, close the modal, and reopen it, the checkbox I clicked on should remain checked. (I am unsure how to achieve this :/) If I check a checkbox and then click t ...

Steps for clearing the chosen input data

I am currently developing an Angular 6 application and I am working on implementing a multiple select feature using just an input box without relying on any third-party plugins, jQuery, datalist, or select boxes. The solution needs to be purely input box b ...

Exploring the connected component feature in React/Redux

While testing the connected component of my React/Redux app, I encountered an error. The test case that caused the error is: App component › shows account info and debits and credits` Invariant Violation: Could not find "store" in either the context or ...

Retrieving Mouse Coordinates using Ajax in PHP

I'm wondering if it's feasible to send an Ajax request with mouse coordinates using PHP. For instance, I am fetching a page with cUrl and would like to trigger a mouse movement event on that page. At this point, I haven't written any code ...

JavaScript: Analyzing the occurrence rate of emojis within text

I'm currently working on a project to tally the frequency of emojis within a body of text. For instance: "I adore ...

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

Struggling to override a css element in a responsive design

Here is a Link that I am having trouble with. Within my CSS, I have an element named tbox. It functions as an inline box with a width set at 100%. On the homepage, it adjusts its width perfectly based on its parent and is fully responsive. However, when na ...

Unexpected "<" and dual output in jade include seem to defy explanation

i am currently redesigning my website to incorporate dynamic includes. These includes are pre-rendered on the server and then passed to res.render() however, I am encountering unexpected occurrences of < and > on the page, along with the issue of th ...

Unraveling the mysteries of the Bootstrap carousel script

Hi everyone, I'm a newcomer to the world of JS and jQuery. Recently, while examining the code in carousel.js, I stumbled upon this particular line: this.cycle(true) The cycle function is structured like this: Carousel.prototype.cycle = function ...

Typescript's universal matching function for discriminated union types

Could a generic match function be defined over discriminated union type? Let's consider the following type declarations: const Kinds = { A: 'A', B: 'B', }; type Kind = typeof Kinds.A | typeof Kinds.B; type Value = A | B; inter ...

The path is visible, yet the ajax call does not make it through - it's simply "off course"

rake routes is used to verify the existence of a route: control1_route1 DELETE /control1/route1(.:format) However, when attempting to make a "delete" request to this route: var url = "<%= control1_route1_url %>"; $.ajax({url: url, type: "D ...