What is the best way to implement a search pipe in Angular 2 that effectively filters a JavaScript object?

Seeking guidance on creating a search pipe for Angular 2 to filter nested objects based on a search term. A basic version is up and running, but encountering two issues.

The first issue involves hard coding key names or resorting to using JSON.stringify, both methods seem less than ideal. Are there more elegant ways to achieve filtering while excluding certain keys like _id and url?

Secondly, struggling with filtering multiple terms when the search string contains space(s) and need to filter objects matching all provided terms. Splitting the search term with spaces is possible using terms = term.split(' '), but unsure how to proceed with filtering by multiple terms.

Current code snippet:

import {Pipe} from 'angular2/core';

@Pipe({
    name: "search"
})
export class SearchPipe{
    transform(obj: any, [term]) {
        if (obj != null && term) {
            return obj.filter( el => {

                //var test = JSON.stringify(el); 
                //return test.toLowerCase().includes(term.toLowerCase()); //trows a compile error but seems to work.

                return el.name.toLowerCase().includes(term.toLowerCase()) || el.place.toLowerCase().includes(term.toLowerCase()) || el.title.toLowerCase().includes(term.toLowerCase()) ;

            });

        } else {
            return obj;
        }
    }
}

Expected input format:

[
{
  "_id": "56ffbe512ba199777d51c6ae",
  "picture": "http://placehold.it/36x36",
  "name": "Melissa Reeves",
  "company": "Orbixtar",
  "place": "Greenwich, Belarus",
  "title": "voluptate est ipsum",
  "location": {
    "lat": -78.926961,
    "lng": 90.157653
  },
  "url": "http://lol.lol"
},
{
  "_id": "56ffbe5119cf66e94b3800b4",
  "picture": "http://placehold.it/36x36",
  "name": "Chelsea Lindsay",
  "company": "Squish",
  "place": "Vowinckel, Belarus",
  "title": "anim ea exercitation",
  "location": {
    "lat": 66.547582,
    "lng": 162.720388
  },
  "url": "http://lol.lol"
}
]

If the term is "term1" it should return objects containing "term1".

For example, the term "Melissa" should only return the first object in the list.

Answer №1

Check out this untested code snippet for searching

@Pipe({
  name: "search"
})
export class SearchFilter{
  transform(data: any, [keyword]) {
    if (data != null && keyword) {
      return data.filter( element => {

        var temp = JSON.parse(JSON.stringify(element));
        delete temp['url'];
        delete temp['_id'];

        var searchString = JSON.stringify(temp);

        Object.keys(temp).forEach(key => {
          searchString = searchString.replace(key, '');
        });

        let termsArray = keyword.replace(/[\s]+/gm, " ").replace(/^[\s]|[\s]$/gm, "").split(' ');
        let matchCount = 0;

        termsArray.forEach(term => {
          if(searchString.toLowerCase().indexOf(term.toLowerCase()) > -1)
          {
            ++matchCount;
          }
        });

        return (matchCount == termsArray.length);
      });

    } else {
      return data;
    }
  }
}

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

The function angular.element() is unable to locate the specified DOM element

My dilemma lies in the fact that I have a dynamic table of users extracted from a Firebase database: <table id="users"> <thead> ... </thead> <tbody> <tr ng-repeat="user in users"> <td da ...

The error message "Uncaught ReferenceError: $foo is undefined, please check your

Currently, I am working on a project to toggle the expansion and collapse of individual divs on a click event using jQuery within the Laravel Spark framework. Most of my code is based on the solution provided in response to this query. Upon clicking the s ...

Testing the functionality of an Angular service using unit tests

Confused about how to test a service in an Angular project that involves a small class with an observer? Can't seem to figure out why the test fails when calling the 'pop' method. Want to ensure that the public methods of this class perform ...

Using nodemailer to send an email with a dynamic variable that holds the HTML content

I am attempting to send a variable containing HTML code from a Vue component using the POST method. My technology stack includes TypeScript, Nuxt.js, Node.js, and Vue.js. const order_list = document.querySelector('table') as HTMLInputElement | n ...

Acquire data from an array of objects using JavaScript

I've written some code where I'm attempting to display certain values in HTML. Specifically, I am looking to extract the values from the "current" object: ("dt":1643884851, "temp":8.11, "description":"few clouds", and "icon":"02d") In addition, ...

Assistance required for setting a value in a mat-select using Angular

Could really use some assistance resolving the issue with mat-select I'm aiming to establish the initial values by utilizing the following code snippet: orders: Order[] = [{"dish":"steak-0"},{"dish":"tacos-2" ...

Is there a way to extract and store the JavaScript Promise value in Selenium as a variable?

Using a JavaScript script, I make an xmlhttprequests call to retrieve a specific value. However, when trying to pass this value back to Selenium for further actions, my code consistently returns None. Even though I have assigned and returned the global var ...

What is the function of 'this' in a code snippet and is it mandatory?

We are in the process of transforming the functionality of PSRunner into a TypeScript function: export function PSRunner(commands: string[]) { const self: { out: string[] err: string[] } = this const results: { command: string; output: any; e ...

What is the maximum character limit for jQuery?

Here's a code snippet I'm working with: $.get("url") .done(function(data){ alert("success"); alert(JSON.stringify(data)); }) .fail(function(data){ alert("fail"); alert(JSON. ...

Using an image for the axis in Wijmo BarGraph

I am currently working with Wijmo barcharts and attempting to create a graph that uses images instead of labels on the x-axis. The code I have at the moment displays the image source as a string rather than displaying the actual image. Does anyone know ho ...

What is the most effective way to ensure a user's email address is not already in my database before submitting a form?

Welcome to my first question post. I'm in the process of creating a test where users can sign in and retake it if they wish. However, I'm facing a challenge in checking whether the user's email already exists in my mariaDB database when they ...

Transforming a Typescript tuple into an object type

Let's consider a scenario where I have a tuple type structured like this: type Data<T extends string, V> = { type: T, value: V }; type TupleExample = [ Data<'string', string>, Data<'number', number>, ...

Issue with Chart.js not showing up in Android Webview when animation is disabled

I am experiencing an issue with a javascript enabled WebView using a ChromeWebClient. The Chart.Js pie example displays fine until I set the options to animation: false, after which the chart stops displaying. var pieOptions = { animation : fa ...

Search through a group of distinct objects to find arrays nested within each object, then create a new object

I am currently working with objects that contain arrays that I need to filter. My goal is to filter an array of classes based on category and division, then return the new object(s) with the filtered arrays. Below is a representation of the JSON structure ...

Experiencing Typescript errors solely when running on GitHub Actions

I've been working on a React+Vite project with the Dockerfile below. Everything runs smoothly when I execute it locally, but I encounter errors like Cannot find module '@/components/ui/Button' or its corresponding type declarations and error ...

Can routes be nested in React components?

I'm curious to know if there's a way to integrate nested routes in React, where the Navbar component serves as the parent for dashboard and properties. <Router> <Routes> <Route path='/' element={<Home />} /> ...

Setting bootstrap datetimepicker values dynamically from a variable

I'm trying to utilize the inline bootstrap datetimepicker from At the moment, it opens in a popup window after the user selects a date/time from a table on another page. My goal is to pass the date/time from that page into datetimepicker and have it ...

Updating views in Angular 2 based on changes in component properties

I recently set up a WebSocket service and component, but I'm facing challenges with updating the view when new data is received through the WebSocket connection. websocket.service.ts import {Injectable} from "angular2/core"; import {Observable} from ...

What is the best method for initializing the value of ng-model as an empty string in AngularJS?

I need help setting the initial value for an attribute in my model. Here's the code I'm using: <input type="text" ng-model="selectedModel.title" name="title" value="" > What I want is for the attribute value to be initially set as an empt ...

the angular variable scope has not been defined

Currently, I am developing an angular controller that is configured to utilize the "controller as" syntax: angular.module('app', []).controller('ctrl1', ctrl1); ctrl1.$inject = ['$http', '$compile']; function ctrl ...