Tips for utilizing array filtering for parent and child elements in Angular 11

I am dealing with an array object and I need to apply certain conditions to fetch the data.

this.knowledgeData = [
    {
        "id": 3,
        "name": "Education",
        "isOtherCategory": 0,
        "isKnowledgeSkills": false,
        "isMyInterest": false,
        "isParentKnowledgeSkills": true,
        "isParentMyInterest": false,
        "subCategories": [
            {
                "id": 96,
                "categoryId": 3,
                "name": "Careers",
                "isOtherSubCategory": 0,
                "isKnowledgeSkills": false,
                "isMyInterest": false
            },
            {
                "id": 97,
                "categoryId": 3,
                "name": "General",
                "isOtherSubCategory": 0,
                "isKnowledgeSkills": true,
                "isMyInterest": false
            },
            {
                "id": 92,
                "categoryId": 3,
                "name": "Home Schooling",
                "isOtherSubCategory": 0,
                "isKnowledgeSkills": true,
                "isMyInterest": false
            },
        ]
    }
]

I utilized the filter option to locate the data that satisfies the conditions.

this.knowledgeData = this.knowledgeData.filter((x)=>{
          if(x.isParentKnowledgeSkills ===true && x?.subCategories?.isKnowledgeSkills ===true){
            return true
          }
        })

However, it is returning empty. I aim to retrieve data where both the parent and child values are true.

The desired result should be as follows:

this.knowledgeData = [
    {
        "id": 3,
        "name": "Education",
        "isOtherCategory": 0,
        "isKnowledgeSkills": false,
        "isMyInterest": false,
        "isParentKnowledgeSkills": true,
        "isParentMyInterest": false,
        "subCategories": [
            {
                "id": 97,
                "categoryId": 3,
                "name": "General",
                "isOtherSubCategory": 0,
                "isKnowledgeSkills": true,
                "isMyInterest": false
            },
            {
                "id": 92,
                "categoryId": 3,
                "name": "Home Schooling",
                "isOtherSubCategory": 0,
                "isKnowledgeSkills": true,
                "isMyInterest": false
            },
        ]
    }
]

This means that the output should only include objects where isKnowledgeSkills is true in the subCategories child array.

Answer №1

My preference would be the following approach:

const filteredData = knowledgeData.filter(item => item.isParentKnowledgeSkills)
    .map(item => ({
        ...item,
        subCategories: item.subCategories.filter(subItem => subItem.isKnowledgeSkills)
    }));
  • Start by filtering out parent data with isParentKnowledgeSkills
  • Then, proceed to filter out child data with isKnowledgeSkills

Link to Playground

Answer №2

revise your if statement

if(x.isParentKnowledgeSkills && x.subCategories.filter((y) => y.isKnowledgeSkills).length){
            return true
          }

Answer №3

The solution has been discovered...

this.knowledgeData = this.knowledgeData.map((i)=>{
          i.subCategories = i.subCategories.filter((x)=> x.isKnowledgeSkills === true)
          return i;
        })

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

Guide on stubbing Google gapi global variable in component tests with Karma

I am currently facing a challenge in setting up tests for a service in my Angular 4 project that utilizes Google gapi. The issue arises from the fact that the variable is globally declared but not mocked, leading to an error when running the tests: Refe ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

Maximizing Angular Route Efficiency

Starting with this particular example, I am laying out my configuration like this: editor.module: .... import { editorRoutingModule } from './editor-routing.module'; import { RouteReuseStrategy } from '@angular/router'; import { myRout ...

Ways to assign a boolean value to HTML using Angular?

Can someone help me set the initial value of showProduct to false for the app-product HTML selector? showProduct:boolean = false; <button (click)="showProduct=!showProduct">Show Product</button> <div *ngIf="!showProduct"> <app-p ...

After a short period of time, the format reveals a completely new value

Can you explain the reason for this unusual behavior? Could it be related to the incoming date format or something else? .html <ion-datetime displayFormat="D MMM, YYYY" [min]="minDate" [max]="maxDate" [ngModel]="data?.dueOn" (ngModelChange)="data.du ...

Angular 17 encountered a select error in core.mjs at line 6531 showing an unexpected synthetic listener error with code NG05105: @transformPanel.done

My select option is not working properly and I keep getting an error in the console that says: To resolve this issue, make sure to import either BrowserAnimationsModule or NoopAnimationsModule in your application. Here's my Typescript code: import { ...

Error: The Angular2 Router is unable to locate the XOutlet outlet in order to load the YComponent

I've encountered an issue while using named router outlets in Angular2 version 2.1.2. The error message I'm receiving is: Cannot find the outlet XOutlet to load 'YComponent' Although the error message is clear, I'm struggling ...

Steps for inserting a dropdown menu into a kendo grid

Hey there, I'm currently working on adding a drop-down list to a kendo-grid column but I'm facing an issue where the data is not loading into the drop-down list. My goal is to populate the data from an array. Here's the code snippet from t ...

What is the correct method to set the root path following a logout?

Just starting out with Ionic and working on creating a login and logout process. Here is the structure: Login: LoginPage => TabsPage Logout: TabsPage => LoginPage Currently, I am handling logging out using this.navCtrl.setRoot(LoginPage). While ...

ngFor returning undefined despite array containing value

While iterating through an array using ngFor, I'm encountering an issue where trying to access data in the 'value' variable results in it being undefined. Why is this happening? myArray = ['a', 'b', 'c', 'd ...

The term 'protractor' is not identified as a valid internal or external command, executable program, or batch file

I have successfully set up Protractor to run from a batch file with the command "protractor conf.js" and the script is functioning correctly. Protractor has been installed globally and all necessary environment settings have been configured. However, when ...

Issue detected in the ngx-joyride package: Error found in ./node_modules/ngx-joyride/assets/images/close.svg

During my build process, I encountered an error with ngx-joyride: ERROR in ./node_modules/ngx-joyride/assets/images/close.svg Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type." <line x1="1" y1=" ...

What is the process for defining a generic function to convert to an array in TypeScript?

Here is a versatile function that wraps any value into an array: const ensureArray = <T,>(value?: T | T[]): T[] => { if (Array.isArray(value)) return value if (value === undefined) return [] return [value] } const undef = undefined ensureAr ...

How do I remove a specific object from my localStorage array in Angular?

Currently, I am storing and retrieving form values from localStorage. When displaying the data, I want to be able to remove a specific object that is clicked on. The issue is that my current code removes all the data instead of just the selected object. Be ...

Trouble encountered with the implementation of setValue on placeholder

When I send the value for age, it is being treated as a date in the API that was built that way. However, when I use setValue to set the form value and submit the form, it also changes the placeholder text, which is not what I want. I would like the placeh ...

trouble encountered when trying to form an array with attributes sourced from a different class (using typescript)

Having trouble creating an array of objects from one class in another class. When I try to push them, an error occurs saying "Cannot read property '0' of undefined." Any help would be greatly appreciated. Here is an example using typescript: exp ...

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request: this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => { this.studentObject = values; }); The studentObject is structured as shown below: { recor ...

The initial character of the input must always be a letter

I need assistance with an input element that requires 5 characters, with the first character being a letter: <input mdInput #acronyme placeholder="Company" type="text" maxlength="5" minlength="5" required [value]="acronyme.value.toUpperCase()"> Th ...

Conditionals in Angular 2 using Sass

Looking to apply this style with Sass or CSS: IF :host.form-control MATCHES .ng-valid[required] OR .ng-valid.required THEN :host ::ng-deep input.form-control = border-left: 5px solid #42A948; Appreciate the help! ...