Exploring Deeply Nested Data Structures in Angular

I'm having trouble searching for the first name, middle name, and last name together. Currently, I can only search for each separately.

For example: When I try to search for "Jacob jj9eqwif Nguyen", it doesn't work. But if I search for Jacob, it works. If I search for jj9eqif, it works. If I search for Nguyen, it works.

Please check out this LINK for more information.

     search(event) {
        const val = event.target.value.toLowerCase();

        if (!val) {
          this.data = this.tempData;
        }

        const temp = this.tempData.filter(row => {
          return Object.keys(row).some(property => {
            if (property === 'received_by') {
              return row[property].fname
                .toString()
                .toLowerCase()
                .indexOf(val) !== -1
                ? row[property].fname
                    .toString()
                    .toLowerCase()
                    .indexOf(val) !== -1
                : row[property].mname
                    .toString()
                    .toLowerCase()
                    .indexOf(val) !== -1
                ? row[property].mname
                    .toString()
                    .toLowerCase()
                    .indexOf(val) !== -1
                : row[property].lname
                    .toString()
                    .toLowerCase()
                    .indexOf(val) !== -1
                ? row[property].lname
                    .toString()
                    .toLowerCase()
                    .indexOf(val) !== -1
                : (row[property].fname + row[property].lname + row[property].mname)
                    .toString()
                    .toLowerCase()
                    .indexOf(val) !== -1;
            }
            if (property === 'warehouse') {
              return (
                row[property].name
                  .toString()
                  .toLowerCase()
                  .indexOf(val) !== -1
              );
            } else {
              return row[property] === null
                ? null
                : row[property]
                    .toString()
                    .toLowerCase()
                    .indexOf(val) !== -1;
            }
          });
        });

        this.data = temp;
      }

Answer №1

There seems to be a typo in your code where you are searching for fname, mname, lname but connecting them as fname+lname+mname. The correct order should be lname at the last position, so make the following change:

(row[property].fname + row[property].mname + row[property].lname)
                .toString()
                .toLowerCase()
                .indexOf(val) !== -1;

Update it to:

(row[property].fname + row[property].mname + row[property].lname)
                .toString()
                .toLowerCase()
                .indexOf(val) !== -1;

In addition, if you prefer a simpler search condition without using a ternary operator, consider the following example:

row[property].fname.toString().toLowerCase().includes(val)
           || row[property].mname.toString().toLowerCase().includes(val)
           || row[property].lname.toString().toLowerCase().includes(val) 
           || (row[property].fname + row[property].mname + row[property].lname)
                .toString()
                .toLowerCase()
                .includes(val);

As pointed out by @Sangram Nandkhile, pay attention to the space between fname, mname, and lname. Your updated condition should look like this:

(row[property].fname +' '+ row[property].mname +' ' + row[property].lname)

Check out the Demo for more information.

Answer №2

Let's begin by reviewing the code you've written:

You utilized Object.key(row) within the filter function, where you checked for only 2 specific properties: recieved_by and warehouse. This led to unnecessary looping through object keys, resulting in wastage of processing resources.

Additionally, you employed multiple ternary operators which can be confusing. It is advisable to simply use the || (or) operator instead.

Here's an alternative solution I propose:

const temp = this.tempData.filter(row => {
  return (
    row.warehouse.name.toLowerCase().indexOf(val) !== -1 ||
    (
      row.received_by.fname + ' ' +
      row.received_by.mname + ' ' +
      row.received_by.lname
    ).toLowerCase().indexOf(val) !== -1
  );
});

Ensure that this code snippet is placed within the search function for it to perform correctly.

You can test this implementation in the following DEMO.

Answer №3

To search for a specific value, concatenate the strings you want to search and then look for the desired value in the combined string.

let results = this.dataArray.filter(item => {
    let concatenatedString = (item.title + " " + item.description + " " + item.category).toLowerCase();
    return concatenatedString.indexOf(searchQuery) >= 0;
}

If you have multiple columns and need to search across all of them, consider using JSON.stringify to convert the entire dataset into a single string for searching.

let results = this.dataArray.filter(item => {
    let jsonString = JSON.stringify(item).toLowerCase();
    return jsonString.indexOf(searchQuery) >= 0;
});

You can view the updated code here - https://stackblitz.com/edit/filter-multiple-wujuvz

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's the significance of & in TypeScript and JavaScript?

While exploring someone else's code, I came across this interesting piece related to the props of a React component. Although I'm aware that & is typically used as an AND logical operator, it seems to have a different significance in this con ...

Typescript is asserting that the React class component has a property, despite what the component itself may suggest

I'm running into an issue with React refs and class components. Here's my simplified code snippet. I have a component called Engine with a property getInfo. In my test, I check for this.activeElement &&, which indicates that it's no ...

Tips for successfully importing mock data for testing without running into reference problems when reusing the same mocked object or array multiple times

Trying to run tests for Angular has presented a challenge. I have intricate objects, nested within other objects, stored in a separate file along with my mocked data. Each mocked object is linked to an export in the data file specifically created for mock ...

I am looking to integrate Firebase app-check into my Angular 12 application. Can anyone guide me on

I have attempted the suggestions provided in this particular inquiry Here is the code snippet I am working with: // firebase-init.ts import firebase from 'firebase/app'; import 'firebase/app-check'; import { environment } from ' ...

Make sure to include the @ symbol before "angular" in the package.json file when setting

Can someone explain to me why the Angular 2 quickstart guide suggests using a package.json file structured like this: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurrently \"npm run tsc:w&bs ...

What is the best way to utilize "exports" in package.json for TypeScript and nested submodules?

Looking to leverage the relatively new "exports" functionality in Node.js/package.json for the following setup: "exports": { ".": "./dist/index.js", "./foo": "./dist/path/to/foo.js" } so that ...

Error in Angular Template Parsing Due to Dynamic Object Key in Angular Version Greater Than 2

When I attempt to assign a value for a key with a variable inside my event binding expression, an unexpected error occurs: Parser Error: Unexpected token [, expected identifier, keyword, or string at column... https://i.sstatic.net/l3Fl5.png the expression ...

Is Angular Template Polymorphism Failing?

So I'm working with a base class that has another class extending it. export class Person { public name: string; public age: number; } export class Teacher extends Person { public yearsTeaching: number; } Now, in my component, I need to ...

Incorporating a new attribute into the JQueryStatic interface

I am trying to enhance the JQueryStatic interface by adding a new property called someString, which I intend to access using $.someString. Within my index.ts file, I have defined the following code: interface JQueryStatic { someString: string; } $.s ...

What methods can be used to deduce the data types of properties buried within multiple

I am currently developing a function that receives a descriptor object and leverages the inferred type information to generate another object with a user-friendly API and strong typing. One issue I have encountered is that TypeScript only infers the types ...

Utilizing React and TypeScript: Passing Arguments to MouseEventHandler Type Event Handlers

Can you help me understand how to properly define the event handler handleStatus as type MouseEventHandler, in order to pass an additional argument of type Todo to the function? interface TodoProps { todos: Array<Todos> handleStatus: Mous ...

Exploring the power of RxJs through chaining observers

In my Angular application, I am utilizing Observables to set up a WebSocket service. Currently, I have the following implementation: readwrite(commands: command[]) : Observable<response[]>{ const observable = new Observable((observer)=>{ ...

Getting a compilation of events attached to a component within Angular

Trying to identify the events being listened to in a component. In this example, event handlers for customEvent1 and customEvent2 are assigned, while customEvent3 remains unused. Is there a way to retrieve this list, particularly within AfterViewInit? & ...

Is jQuery utilized by the bootstrap-grid system?

Finale: In our current setup, we are utilizing Angular 9, and like many frontend frameworks, there is a preference against incorporating other JavaScript libraries alongside the framework for manipulating the DOM. The Challenge: I am hesitant to include ...

tsc does not support the use of the '--init' command option

Encountering an error when running npx tsc --init: $ npx tsc --init npx: installed 1 in 1.467s error TS5023: Unknown compiler option 'init'. I've added the typescript package using Yarn 2: $ yarn add -D typescript ➤ YN0000: ┌ Resolution ...

I am facing an issue with Adal.service.ts in Angular while running tests using Jest, it's not working as expected

Can someone help me, please? I'm in the process of migrating to Jest for running unit tests on Angular. However, when I try to execute the tests, I encounter the following error: FAIL src/app/modules/dashboard/components/navbar/navbar.component.spec. ...

The CORS policy is causing a blockage for the front-end application due to the Spring Boot backend

Currently working with Spring Boot and Angular. I have included the cross-origin annotation in my code to allow access from my Angular localhost port, but unfortunately, I am still encountering the following error: https://i.sstatic.net/4uDuv.png Here is ...

Exploring Angular's powerful routing feature: lazy loading modules with loadChildren

I am developing an Ionic app that includes tabs and a login page. The tabs are structured in their own module with a routing module for each tab. Upon launching the app, I want users to be directed to the login page first. After successfully logging in, ...

Is NgForm considered a directive within Angular - is it a structural or attribute directive for components?

I'm new to this, so please bear with me. According to https://angular.io/guide/attribute-directives: Angular has three types of directives: Components – directives that come with a template. Structural directives – alter the DOM layout by adding ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...