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

How can I enable editing for specific cells in Angular ag-grid?

How can I make certain cells in a column editable in angular ag-grid? I have a grid with a column named "status" which is a dropdown field and should only be editable for specific initial values. The dropdown options for the Status column are A, B, C. When ...

Limiting File Access for a Google Cloud Platform Bucket Using Node.js

Below is the code for my fileUploadService: import crypto from 'crypto'; var storage = require('@google-cloud/storage')(); uploadFile(req, bucket, next) { if (!req.file) { retur ...

When trying to reference a vanilla JavaScript file in TypeScript, encountering the issue of the file not being recognized

I have been attempting to import a file into TypeScript that resembles a typical js file intended for use in a script tag. Despite my efforts, I have not found success with various methods. // global.d.ts declare module 'myfile.js' Within the re ...

Issue with TypeScript when calling the jQuery getJSON() method

Currently, I am working with TypeScript version 1.7.5 and the latest jQuery type definition available. However, when I attempt to make a call to $.getJSON(), it results in an error message stating "error TS2346: Supplied parameters do not match any signatu ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

Visiting route/id does not automatically trigger a template update (the address bar displays the correct route/id)

As I dive into learning Angular, I apologize in advance if my question seems basic. I am working on a simple app with a left-side panel (using Sidenav Material component) and a content area. The left-side panel displays a list of machines (MachineComponent ...

Observing the route parameters in an Observable stops once a 404 error is triggered from another Observable within a switchMap

In my current scenario, I am monitoring the parameters of the active route in order to update the content being displayed. Within my component's ngOnInit() function, I have implemented the following logic: this.activeRoute.paramMap .pipe( ...

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

Ways to enhance a component by utilizing ChangeDetectorRef for one of its dependencies

I am in the process of expanding a component and one of its dependencies is ChangeDetectorRef export class CustomBgridComponent extends GridComponent implements OnInit { @Input() exportFileName: string = ''; constructor( ..., change ...

Karma test parameter "watch=false" is not functioning as expected

We encountered an issue while running our Jasmine tests. When we execute: ng test --browsers=ChromeHeadless --code-coverage the tests are successful. However, if we run: ng test --watch=false --browsers=ChromeHeadless --code-coverage it fails and we r ...

Taking ASP.NET Core 2.0 with Angular to CloudFoundry

Currently, I am facing an issue while working on an app in CloudFoundry (CF). Whenever I push my code into CF, I encounter an error indicating that NodeJs is not installed. [APP/PROC/WEB/0] ERR [1] Ensure that Node.js is installed and can be found in one ...

The service subscription in the ngOnInit lifecycle hook is only invoked once and does not remain populated when the route changes

I need some clarification. The Angular app I'm working on is successfully populating data to the view, but when navigating from one component to another, the ngOnInit lifecycle hook doesn't seem to be invoked, leaving the list on the view empty. ...

Guide to creating a personalized pipe that switches out periods for commas

I currently have a number with decimal points like --> 1.33 My goal is to convert this value so that instead of a dot, a comma is displayed. Initially, I attempted this using a custom pipe but unfortunately, it did not yield the desired result. {{get ...

The issue with making an HTTP POST request in Angular 2

Service: postJson() { var json = JSON.stringify({ "key": "CT", "values": ["FSP", "HMC", "PHYP","hell"] }); let headers = new Headers({'Content-Type':'application/json'}); //let options = new RequestOptions({ ...

Unable to utilize the forEach() function on an array-like object

While I generally know how to use forEach, I recently encountered a situation that left me puzzled. Even after searching online, I couldn't find any new information that could help. I recently started delving into TypeScript due to my work with Angul ...

What is the ideal configuration for Typescript within ASP.NET 4 MVC 5 on Visual Studio 2015?

Currently, I am in the process of integrating a TypeScript project into a VS2015 MVC 5 project (which is based on ASP.NET 4, specifically not asp.net 5 or asp.net 6 - only the MVC portion is version 5). All aspects of my query pertain solely to this target ...

Ways to show a child's component element within the parent container

Within my Angular 11 project, there exists a component that exhibits a child component containing assorted table filters: Parent Component <table-filters></table-filters> <table> ... </table> Child Component (table-filters) <f ...

What is causing pre-defined variables to act unexpectedly in Cypress?

Encountering unexpected results while pre-defining element variables and using them later in Cypress 10 with Cucumber. Let's take a look at this login test: Given("I'm logged in as Default user", () => { cy.visit('/ ...

Encountering difficulty importing TypeScript files dynamically within a Deno executable

When attempting to import a file from aws in an exe using its public link based on user input, I am facing difficulties For example, I generated my exe with the command below deno compile --allow-all main.ts Users execute this exe using commands like ./e ...