Utilizing Angular Pipe filter to search a nested array using multiple key combinations

Within my application, there are 3 search fields available: username, organisation, and active status (boolean). When the search button is pressed, a table is filtered using a combination of these values or by a single search query.

The Json data structure:

[
    {
        "id": 1,
        "userName": "abc",
        "active": true,
        "organisations": [{
            "id": 2,
            "organisation": "org1"
        },
        {
            "id": 3,
            "organisation": "org2"
        }]
    },
    {
        "id": 2,
        "userName": "def",
        "active": true,
        "organisations": [{
            "id": 4,
            "organisation": "org4"
        },
        {
            "id": 5,
            "organisation": "org5"
        }]
    },
    {
        "id": 3,
        "userName": "ghj",
        "active": false,
        "lastLogon": "",
        "organisations": [{
            "id": 6,
            "organisation": "org6"
        },
        {
            "id": 7,
            "organisation": "org7"
        }]
    }
]

The Filter logic:

@Pipe({name: 'searchfilter'})
export class SearchFilterPipe implements PipeTransform {
    transform(items: Array<any>, filter: {[key: string]: any }): Array<any> {
        return items.filter(item => {
                let notMatchingField = Object.keys(filter)
                                             .find(key => item[key] !== filter[key]);

                return !notMatchingField;
            });
    }
}

The Html implementation:

<tr *ngFor="let user of users | searchfilter: tableFilter;">
     <td>{{ user.userName }}</td>
     <td><input type="checkbox" [checked]="user.active"></td>
</tr>

The tableFilter object allows for a single search field or a combination of two or three fields. For example: tableFilter = {"userName":"abc"} or tableFilter = {"userName":"abc", "active": true} or tableFilter = {"userName":"abc", "organisation:"org6", "active": true}.

While my code successfully filters based on username, active status, or both, it encounters issues when attempting to filter by organisation due to the nested array structure.

Any assistance with optimizing the Pipe filter functionality would be greatly appreciated. I have heard of the library Lodash but am unsure how to integrate it into my code. Thank you in advance.

Answer №1

Could you please test the code snippet below?

 export class SearchFilterPipe implements PipeTransform {
  transform(items: Array<any>, filter: { [key: string]: any }): Array<any> {
    return items.filter(item => {
      return this.checkItem(item, filter);
    });
  }

  checkItem(currentItem: any, filterItem: any): boolean {
    let keysInFilter = Object.keys(filterItem).find(filterKey => {
      let isItemFound = false;
      if (filterKey === 'organisation') {
        isItemFound = currentItem?.organisations.find((orgItems: any) => orgItems[filterKey] === filterItem[filterKey]) !== null;
      } else {
        isItemFound = currentItem[filterKey] === filterItem[filterKey]
      }

      return isItemFound;
    })

    return Object.keys(filterItem).length === keysInFilter?.length;
  }

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

Toggling Selected Items with Jquery Show/Hide Feature

Is there a way to toggle the visibility of selected items in the mobile menu? For instance, when I click on the menu toggle, I would like all the items in the Div class sidebar to be displayed but any content within its child div with class="sticky" shoul ...

What is the best way to implement CSS properties on Material UI components?

I've recently started exploring Material UI, but I'm having trouble understanding how the spacing properties function. I'm trying to utilize the "spacing" feature for various elements, but it appears that it only works for "Box" components a ...

Issue with Angular2 Property Change Notification

I have a directive called app.service.ts that holds the state data of the app. I'm using this directive in other components to access and modify the app state, which is functioning correctly. However, I encounter an error when I attempt to bind a pro ...

JavaScript encountered an abrupt cessation of input, catching us off guard

Can someone please help me identify the issue with the JavaScript code below? I encountered an error message stating "Unexpected end of input", but upon reviewing the code, I couldn't find any apparent errors. All my statements seem to be properly ter ...

Angularjs encounters an abrupt stop in the expression during an ng-keypress event

In my code, I am utilizing the ng-keypress directive to monitor whether the ENTER key has been pressed. ... ... <input type="text" ng-model="mymodal" ng-keypress="($event.charCode==13)?myFunction():return"/> ... ... However, upon opening the p ...

Steps for writing/appending the JSON object from a POST request to a JSON file

I'm looking to update a JSON file by adding a new element using data from a POST request. The process is mostly working, but I'm struggling with including the id in the data. Can anyone help me figure this out? I've tried various approaches ...

What could be causing the old value to persist in angular $scope and not get removed

In my controller, I have defined the following: angular.module('publicApp') .controller('URLSummaryCtrl', function ($scope, $location, Article, $rootScope, $timeout) { $scope._url = ""; $scope._title = ""; $scope._article ...

Issues arose when attempting to parse corrupt JSON data sent from PHP to AJAX

I'm currently facing a challenge with parsing JSON data sent by PHP. Here is the JSON data: [{"id":"1","value":"1"},{"id":"4","value":"1"},{"id":"2","value":"1"},{"id":"3","value":"1"},{"id":"4","value":"1"}] My goal is to parse this data, extract ...

How can we store image file paths in MongoDB?

I'm currently working on developing a REST API using nodeJS, express, mongoose, and mongodb. I have successfully implemented file uploads with multer and saved the files to a folder. Now, I need to save the path of the uploaded file to a mongodb docum ...

Tips for showing chosen options in react-select multi component?

I am incorporating react-select with isMulti functionality, where a list of options is provided. My goal is to have certain options automatically selected by default if they match the values in a given array. import React, { useState } from "react"; imp ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

Exploring the Power of NPM Modules in an Electron Renderer

Having trouble accessing lodash in an electron renderer. I'm a beginner with Electron and know that both the main process and renderer (local html file) have access to node. I can require something from node core like fs and it works fine, but when I ...

How can we eliminate the 'www' in a URL using NodeJS and Express?

What is the best way to eliminate the 'www' in a URL using NodeJS + Express? For instance, when a client connects to , how can we automatically redirect them to without the 'www'? ...

Differences Between NgModule and AppComponent in Angular

Being a novice in the realm of Angular, I'm curious to know the distinction between CommonModule and BrowserModule, and when one should be prioritized over the other. ...

Creating a custom arrow design for a select input field using CSS

I'm currently developing a website (using Wordpress with a custom theme) and I want to incorporate an up/down arrow in the select input field using CSS. The HTML code I have for creating the up/down arrow in the select input field is as follows: < ...

Tips for transferring an array from a form to a URL using JavaScript?

My form uses a get method, and includes a select element allowing users to choose multiple options. However, when the user submits the form, the URL does not neatly display these selections. Is there a way for me to pass the array in a more organized manne ...

Validate forms using jQuery with the power of ajax

Is there a way to effectively check for the existence of a username? I want to increment a variable called "form_error" if the username already exists. If "form_errors" is greater than 0, I need the code to stop and return false. However, when I use an Aj ...

The Angular 2 view appears on the screen before the data finishes loading in the ngOnInit

Utilizing the github API in my angular 2 application, I encounter an issue where the view renders before ngOnInit has finished loading data. This leads to a Cannot read property of undefined error. The relevant portion of my code is as follows: ngOnInit() ...

Unexpected lack of parameters in a function triggered by an event listener's callback

I am currently working with a functional react component where I am attempting to attach events to multiple elements simultaneously. However, I am encountering issues with passing a trigger element to a function. export default function Header() { cons ...

The API response indicating success is simply denoted as "Success: True", without any accompanying data

I've set up my application on an express server with a proxy to communicate with the API server. Here's a snippet of my code: HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...