Oops! It seems like there is an issue with reading the property 'filter' of an undefined object. Any ideas on how to resolve this error

Having an issue with a custom filter that is causing an error "

ERROR TypeError: Cannot read property 'filter' of undefined
". I need help fixing this as it's preventing anything from rendering on the page. Any suggestions on what changes I should make to correct this? Your assistance is greatly appreciated.

File: table-filter.pipe.ts

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "tableFilter"
})
export class TableFilterPipe implements PipeTransform {
  transform(list: any[], filters: any) {
    //console.log("table-filter", list);
    const keys = Object.keys(filters).filter(key => filters[key]);
    const filterUser = (user: { [x: string]: any }) =>
      keys.every(key => {
        if (key == "sdob") {
          return (
            new Date(user["dob"]) >=
            new Date(new Date(filters[key]).setHours(0, 0, 0, 0))
          );
        } else if (key == "edob") {
          return (
            new Date(new Date(filters[key]).setHours(0, 0, 0, 0)) >=
            new Date(user["dob"])
          );
        } else if (
          key === "dl" &&
          user["assigned_to"].filter((e: { dl: any }) => e.dl === filters[key])
            .length
        ) {
          return user;
        } else if (key === "score") {
          const low = filters[key] === "20" && user["score"] <= filters[key];
          const medium =
            filters[key] === "50" && user["score"] < 50 && user["score"] >= 21;
          const high =
            filters[key] === "70" && user["score"] < 70 && user["score"] >= 51;
          const veryHigh = filters[key] === "71" && user["score"] >= 71;
          if (low || medium || high || veryHigh) {
            return user[key];
          }
        } else {
          return user[key] === filters[key];
        }
    });    

    if(list) {
      let filterList = list.filter(filterUser);
      list.sort((lhs, rhs) =>this.lowestScore(lhs.assigned_to) - this.lowestScore(rhs.assigned_to));
    }

    return keys.length ? list.filter(filterUser) : list;
  }
  
  lowestScore(assign: any) {
    let filterData = assign.filter(item => Number(item.co_score));
    let leastScrore = Math.min(...filterData.map(item => item.co_score));
    return leastScrore;
  }
}

Answer №1

The issue arises when trying to use the ".filter" method on an undefined object. This error can be found in the following lines:

const keys = Object.keys(filters).filter

  • This will result in failure if the "filters" object has no keys. If you are not passing filters to your transform function, this is a probable cause.

user["assigned_to"].filter

  • If user does not have the specified property or if it is not an array, this line will fail.

let filterData = assign.filter

  • If lowestScore is passed as undefined, then this line will fail.

Answer №2

The issue arises from the following error message:

return keys.length ? list.filter(filterUser) : list;

If your list is undefined but you have keys, it will attempt to execute list.filter. However, since list is undefined, this results in an error.

Answer №3

If the browser you're using allows, you have another option:

return list?.filter(filterUser) || list

Answer №4

Consider trying to install:

ng generate pipe searchFilter

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

issue with visibility of checkbox in material ui table row

In a separate file called TradesTable.js, I have created a table using Material UI for my React app. const DummyTableRow = (props) => { let myRows = props.trades.map((trade, index) => { return <TableRow> <TableRowColumn ...

Transforming a CSV document into a JSON format in order to generate a hierarchical tree structure for constructing a D3 categorical tree diagram

I have a CSV file that is structured like this: "","Sequence","Paths","sequence_length" "1","Social -> Social -> Social -> Social -> Social -> Social -> Social -> Social",29,8 "2","Social -> Social -> Social -> Social -> S ...

Adding text with jQuery

Currently, I am utilizing the Jquery text editor plugin known as JqueryTE. While adding some functions to it, I have encountered a roadblock. Specifically, I am attempting to insert additional text into the source of the textarea but have been unsuccessfu ...

Is there a way to achieve region collapsing and expanding using #region / #endregion in TypeScript within Visual Studio Community Edition 2019?

For a while now, we've been utilizing "region collapsing" in TypeScript as shown below: //#region GUI handlers ...code related to handling GUI events... //#endregion This method has functioned well in VS2015 CE and VS2017 CE, with a small "-" or "+" ...

Showing a series of JavaScript countdowns consecutively

I am working on a project where I want to display a second countdown after the first one finishes using meteor. The initial timer code looks like this: sec = 5 @timer = setInterval((-> $('#timer').text sec-- if sec == -1 $('#time ...

Chrome Extension: Sending Data from Panel Window to Popup - A Step-by-Step Guide

I've been developing a Chrome extension that displays a window (popup.html) containing a button for playing videos when the extension icon is clicked. Upon clicking the play button, another window created using window.create of type panel opens up. Th ...

How to access variables with dynamic names in Vue.js

I'm curious if it's possible to dynamically access variables from Vue’s data collection by specifying the variable name through another variable. For instance, consider the following example: Here are some of the variables/properties: var sit ...

What steps should I follow to incorporate channel logic into my WebSocket application, including setting up event bindings?

I'm currently tackling a major obstacle: my very own WebSocket server. The authentication and basic functionality are up and running smoothly, but I'm facing some challenges with the actual logic implementation. To address this, I've create ...

How to transfer a parameter in Angular 2

I am currently facing a challenge in passing a value from the HTML file to my component and then incorporating it into my JSON feed URL. While I have successfully transferred the value to the component and displayed it in the HTML file, I am struggling to ...

In Typescript, try/catch blocks do not capture return values

I am currently working on a function that performs database operations, with the implementation contained within a try/catch block. Here is an example: async function update({id, ...changes}): Promise<IUserResult> { try { //insert code here retu ...

Can we access global variables directly in an Angular 2 HTML template?

After setting the app.settings as shown below public static get DateFormat(): string { return 'MM/DD/YYYY';} I need to utilize it in one of my HTML templates for a component. This is what I want to achieve. <input [(ngModel)]="Holiday" [dat ...

Add items to QueryList in Angular

For my project, I am facing a challenge of combining two QueryLists. The issue is that I have multiple mat-options, with some being provided through ng-content outside the component and others inside the component itself. Essentially, I need to merge both ...

In Angular, a white screen may suddenly appear if the scrolling speed is too fast

My experience has been primarily on Chrome. I've noticed that when I scroll for a long time, the data on the screen disappears briefly and then reappears after a few seconds. Is there a resolution for this problem? Thank you, ...

Using TypeScript with React may result in an error message stating that a string cannot be assigned to a parameter of type 'keyof T'

I've encountered an issue with my sorting function that I built using TypeScript and React Hooks. The error message I'm getting is: Argument of type 'string' is not assignable to parameter of type 'keyof T'. Type 'stri ...

I'm having trouble establishing a connection with the Appwrite platform

Encountered an issue while trying to connect to appwrite. The specific error message is: Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL at Account.<anonymous> (appwrite.js?v=d683b3eb:932:19) at Generator.nex ...

Exploring the attributes of a record through a combination of string template types

I'm utilizing a string template type to denote ids with a significant prefix, such as dta-t-${string} where dta-t- encodes certain details about the entity. I have various record types that are indexed by unions of string templates: type ActivityTempl ...

showing information on webpage 2 received via query parameters from webpage 1

Hello, I am trying to input text into a textarea and then send the data through a query string to another webpage. My goal is to display the data on the second webpage. I have written the following code, but it doesn't seem to be working. I've ch ...

Ways to pause for the completion of multiple HTTP promises and display a modal exclusively when all promises result in failure

There are two separate HTTP calls on a page that need to be handled independently. vm.$onInit = function() { .... .... //Retrieve all items during initialization ds.getAllItems().then(function(result){ vm.items = result; },funct ...

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

What is the most effective way to handle DOM events in Angular 8?

Looking to listen for the 'storage' event from the window in Angular 8. What is the recommended approach to achieving this in Angular? window.addEventListener('storage', () => { }); One method involves using Renderer2, but are ther ...