Enhancing search capabilities in Angular 8.1.2 by filtering nested objects

I am in need of a filter logic similar to the one used in the example posted on this older post, but tailored for a more recent version of Angular.

The filtering example provided in the older post seems to fit my requirements perfectly, especially with nested JSON objects that are 4 levels deep. However, I am struggling to implement the same functionality in my Angular 8 solution.

This is how my data structure looks:

[{
"name": "Repair Category Name",
"image": "https://via.placeholder.com/150",
"subCategories": [
  {
        "name": "Repair SubCategory Name 1",
        "image": "https://via.placeholder.com/150",
        "selectorOptions": [
          {
            "name": "Repair Selector Option 1",
        "image": "https://via.placeholder.com/150",
        "repairItems": [
            {
              "name": "Repair Item 1",
              "image": "https://via.placeholder.com/150",
              "sorCode": "12345"
            },
            {
              "name": "Repair Item 2",
              "image": "https://via.placeholder.com/150",
              "sorCode": "12345"
            }
      ]
          }
      ]
    },
    {
        "name": "Repair SubCategory Name 2",
        "image": "https://via.placeholder.com/150",
        "selectorOptions": [
          {
            "name": "Repair Selector Option 1",
        "image": "https://via.placeholder.com/150",
        "repairItems": [
            {
              "name": "Repair Item 1",
              "image": "https://via.placeholder.com/150",
              "sorCode": "12345"
            },
            {
              "name": "Repair Item 2",
              "image": "https://via.placeholder.com/150",
              "sorCode": "12345"
            }
      ]
          }
      ]
    }
]}]

My goal is to filter by the name or SOR code of the RepairItem and retrieve the complete sub and parent objects to display the results under their respective categories on the UI.

Here is what I have attempted so far: Stackblitz

Any assistance would be highly appreciated!

Thank you

Answer №1

Retrieve the name, age, and subCategories, then loop through the subCategories and use filter on the repairItems.

const data = [{
    "name": "Repair Category Name",
    "image": "https://via.placeholder.com/150",
    "subCategories": [
        {
            "name": "Repair SubCategory Name 1",
            "image": "https://via.placeholder.com/150",
            "selectorOptions": [
                {
                    "name": "Repair Selector Option 1",
                    "image": "https://via.placeholder.com/150",
                    "repairItems": [
                        {
                            "name": "Repair Item 1",
                            "image": "https://via.placeholder.com/150",
                            "sorCode": "12345"
                        },
                        {
                            "name": "Repair Item 2",
                            "image": "https://via.placeholder.com/150",
                            "sorCode": "12345"
                        }
                    ]
                }
            ]
        },
        {
            "name": "Repair SubCategory Name 2",
            "image": "https://via.placeholder.com/150",
            "selectorOptions": [
                {
                    "name": "Repair Selector Option 1",
                    "image": "https://via.placeholder.com/150",
                    "repairItems": [
                        {
                            "name": "Repair Item 1",
                            "image": "https://via.placeholder.com/150",
                            "sorCode": "12345"
                        },
                        {
                            "name": "Repair Item 2",
                            "image": "https://via.placeholder.com/150",
                            "sorCode": "12345"
                        }
                    ]
                }
            ]
        }
    ]
}];

const searchKey = "12345";

const {name, image, subCategories} = data[0];

let filteredResults = [];

subCategories.forEach(({selectorOptions}) => {
    const matchedItems = selectorOptions[0].repairItems.filter(({sorCode}) => sorCode === searchKey);
    filteredResults.push(...matchedItems);
});

console.log([{name, image, subCategories: [ ...filteredResults]}]);

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

Update the name of the table header dynamically based on the checkbox that is selected in Vue

I am working on a project where I have checkboxes that determine the header of my table based on selection. Starting from <th>Default</th>... If checkbox1 is checked, the header will change to "CheckBox1". If checkbox2 is checked, the header ...

Oops! The formGroup function in Angular 5 requires an instance of a FormGroup

While working with Angular 5, I encountered an error in this basic form. Here is the issue: Error Message: EditVisitanteDialogComponent.html:10 ERROR Error: formGroup expects a FormGroup instance. Please pass one in. Example: > > &l ...

Continuously apply the template in a recursive manner in Angular 2 without reintroducing any duplicated components

Recently, I delved into the world of angular 2 and found it to be quite fascinating. However, I'm currently facing a roadblock and could really use some assistance. The scenario is as follows: I am working on creating a select box with checkboxes in ...

What is the process for specifying a data type for a pre-existing npm package module?

I am currently working on converting a codebase that utilizes nodemailer along with the nodemailer-html-to-text plugin to TypeScript. While nodemailer has @types definitions available, the same is not true for nodemailer-html-to-text. How can I go about ...

Ways to boost the efficiency of your Ionic 4 app development process

I have created an Ionic 4 app with over 50 screens, including components and popups. The build and live reload process is taking a lot of time, especially for minor UI changes. Is there a way to speed up the development process? Here are my Environment Se ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...

What kind of impact on performance can be expected when using index.ts in a Typescript - Ionic App?

When setting up the structure of a standard Ionic app, it typically looks like this: app pages ----page1 ---------page1.ts ----page2 ---------page2.ts If I were to include an index.ts file in the pages folder as follows: pages/index.ts export { Page1 } ...

The name 'BrowseAnimationModule' cannot be located

Can someone help me figure out how to install or fix this import issue I'm having with the 'animations' directory in @angular/platform-browser/animations not importing properly? import {CommonModule} from '@angular/common'; import ...

The React Quill interface is unable to load due to an undefined window

I recently integrated React Quill into my Next.js project and everything was functioning properly. However, I encountered an issue when attempting to incorporate ImageResize into the editor. Upon adding the line Quill.register('modules/imageResize&ap ...

Guide on how to showcase the template by leveraging the roomList information with ngTemplateOutlet in Angular

TS roomList = [{ name: 'Room2' }] HTML <div class="Layout-body"> <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="Room1" [ngTemplateOutletContext]="{ data: dt, i: i }&qu ...

What is the process for automatically initiating a service when importing a module in Angular?

I am curious about how I can automatically run a service within a module upon importing it, without the need for manual service injection and execution. This functionality is similar to how the RouterModule operates. @NgModule({ imports: [ Browser ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

Tips for refreshing the service page in Ionic 2

One of my services is called "user-data", and its main function is to fetch "user data" when a request is received. I have a specific page that is responsible for displaying this "user data". Upon loading the page, it retrieves the data and displays it. ...

Angular can be used to compare two arrays and display the matching values in a table

Having two arrays of objects, I attempted to compare them and display the matching values in a table. While looping through both arrays and comparing them by Id, I was able to find three matches. However, when trying to display these values in a table, onl ...

Tips for minimizing disagreements while implementing optional generic kind in TypeScript?

An issue arises in StateFunction due to its optional second generic type that defaults to a value. Even when omitting this second generic, undefined still needs to be passed as an argument, which contradicts the idea of it being optional. While making arg ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Encountering SUID Sandbox Helper Issue When Running "npm start" on WSL with Electron and Typescript

Can anyone help me with this issue? I have Node v8.10.0 and I'm attempting to follow a beginner tutorial on Electron + Typescript which can be found at the following link: https://github.com/electron/electron-quick-start-typescript Here is the full e ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...