Searching for values within an array of objects by iterating through nested arrays to apply a filter

Having trouble returning the testcaseid from an array to this.filteredArray

Able to fetch header value and all values of the array when the search word is empty.

Seeking assistance with iterating through the testcaseid and header on the search input field.

Array -

 PanelList$: any[] =
[
   {
      "header":"header1",
      "data":[
         {
            "testcaseId":"tz_param",
            "description":"tz_param"
         },
         {
            "testcaseId":"tzication",
            "description":"tzication"
         }
      ]
   },
   {
      "header":"security",
      "data":[
         {
            "testcaseId":"tz_prompt",
            "description":"tz_prompt"
         },
         {
            "testcaseId":"z_Root_CA",
            "description":"z_Root_CA"
         },
         {
            "testcaseId":"tz_part1",
            "description":"tz_part1"
         }
      ]
   }
]

Search input code -

 <input matInput (keyup)="applyFilter($event.target.value);" autocomplete="off" placeholder="Search Test Cases...">

Filter Function - used to search through header and testcase id

applyFilter(filterWord) {

let arraycase;
let arraycase1;

const word = filterWord.toString().toLowerCase();

this.filteredArray = this.PanelList$.filter(his => {

    if(his.header.toString().toLowerCase() ===  word) {
      console.log('1' + 'header')
      return his}


    if(his.header.toString().toLowerCase().includes(word)) {
      console.log('2' + 'return full array')
      return his}

   his.data.filter(ids => { 

      if(ids.testcaseId.toString().toLowerCase() ===  word) {
        console.log('3')

        arraycase = [{header: his.header, data: [ids] }]
        console.log(arraycase);
        return  arraycase
      } {

      return  arraycase
      }
      
    })

    console.log(arraycase1 + 'asdads');
  
})

Update 1 -

      this.PanelList$ = JSON.parse(msg.data);
      this.filteredArray = JSON.parse(msg.data);

Both this.PanelList$ and this.filteredArray have the same array content.

Answer №1

Here is the finalized response to my query - I have successfully retrieved the expected value-

applyFilter(filterValue) {
    console.log(this.PanelList$);
    let filteredResult;
    const word = filterValue.toString().toLowerCase();

    this.filteredArray = this.PanelList$.map((item) => {
      if (item.header.toString().toLowerCase() === word || item.header.toString().toLowerCase().includes(word)) {
        return item;
      }

      filteredResult = [];

      item.data.filter((id) => {
        if (id.testcaseId.toString().toLowerCase() === word) {
          filteredResult = { header: item.header, data: [id] };
          console.log(filteredResult);
          return filteredResult;
        }
      });
      return filteredResult;
    });


    if (this.filteredArray[0].length === 0) {
      this.testCaseIdTable = true;
    }
  }

Answer №2

Due to the absence of your entire code, I have made necessary adjustments for testing purposes and to provide you with an insight into how you can modify your code.

  //applyFilter(filterWord) {

let arraycase;
let arraycase1;

PanelList =
[
   {
      "header":"TestBootNotification_CS",
      "data":[
         {
            "testcaseId":"tc_real_module_param",
            "description":"tc_real_module_param"
         },
         {
            "testcaseId":"tc_BootNotification",
            "description":"tc_BootNotification"
         }
      ]
   },
   {
      "header":"security",
      "data":[
         {
            "testcaseId":"tc_with_prompt",
            "description":"tc_with_prompt"
         },
         {
            "testcaseId":"tc_install_Root_CA",
            "description":"tc_install_Root_CA"
         },
         {
            "testcaseId":"tc_install_client_cert_part1",
            "description":"tc_install_client_cert_part1"
         }
      ]
   }
]

   
  var word =  "TestBootNotification_CS".toString().toLowerCase();  //filterWord.toString().toLowerCase();

this.filteredArray = 
PanelList.map( 
    (his) => {

        if(his.header.toString().toLowerCase() ===  word) {
          console.log('1' + 'header')
          return his}
    
    
        if(his.header.toString().toLowerCase().includes(word)) {
          console.log('2' + 'return full array')
          return his}
    
          arraycase = [] 
          his.data.filter(ids => { 
    

          if(ids.testcaseId.toString().toLowerCase() ===  word) {
            console.log('3')
    
            // arraycase = [{header: his.header, data: [ids] }]
            var obj = {header: his.header, data: [ids] }
            arraycase.push( obj )
            console.log(arraycase);
            return  arraycase
          } else {
    
          return  arraycase
          }
          
        })
    
        console.log(arraycase1 + 'asdads') 
    }
 

 )



console.log( this.filteredArray  ) 

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

Enhance the performance of React code by refactoring it

Having recently started coding in React for a new organization, I find that the code in my component has grown lengthy and the submithandler method is causing multiple array iterations. Is there a way to refactor the code for better performance? The data t ...

Use jQuery to parse the JSON below and then showcase the information in an HTML table

Can anyone assist me with parsing the following JSON using jQuery and presenting it in an HTML table? I want to showcase the values of "key" and "doc_count" in an HTML table. Your help would be greatly appreciated. Please find the JSON data below: { ...

Tips on updating the datepicker format to be dd/mm/yyyy in ngbdatepicker

I am currently using ng-bootstrap for a datepicker and need to change the date format from yyyy/mm/dd to dd/mm/yyyy. I have tried to make this adjustment but haven't had success. If anyone has suggestions on how to accomplish this, please help. Here ...

What is the best way to get the number of populated children in a Mongoose schema?

Hello all, I am just beginning to learn about MongoDB and Mongoose. Does anyone know of a simple method to count the answers for each topic after using the population method? var query = Topic.find({}); query.select("title answersRef"); query.populate({p ...

Steps for incrementing a number in an integer field with Node.js and MongoDB

I have a dataset that looks like this: { "_id": "6137392141bbb7723", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7e7fafafef0d5f6f4f2f9f0bbf6faf8">[email protected]</a>", ...

Encountering Compilation Issues Post Upgrading to Angular 9

I recently upgraded my Angular application from version 8 to version 9, following the official guide. However, after the upgrade, I encountered errors that prevent my application from building. The specific errors include: "Module not found: Error: Can ...

transmit JSON formatted form data to an AngularJS platform

I have a webpage built on AngularJS with a login feature. I want to iframe this webpage onto my own page and automatically log in my users. Upon inspecting the AngularJS site, I noticed that the login procedure expects a json object. I have tried multipl ...

Acquire information from the user interface and display it in a highcharts chart using Angular 5

Currently, I am utilizing an npm package for chart creation, which can be found at the following link: https://www.npmjs.com/package/angular-highcharts I have a specific interface set up and I aim to extract values from this interface to populate a line g ...

Image paths becoming unresponsive following package upgrades

My Angular2 application was originally built using angular-cli (v 1.0.0) and webpack2. Within a component, I had the ability to reference an image like so: <div class="country-flag"> <img [src]="src/assets/flags/32/jp.png" [width]="flagIconSiz ...

Vercel Next JS features server and client components with distinct timezones

In my Next.js 13.2.4 project, there is a useful helper function named getLocalTime(date) that retrieves the local time of the user's machine in a specific format. //Desired output: 9:30PM export function getLocalTime(date) { const localTime = new D ...

HTML-Formatted Email Content

Similar Question: MailTo with HTML body I am looking to utilize JavaScript to send emails. I came across this helpful post: Sending emails with JavaScript. My goal is to include images, bold text, and color changes in the email content. Does anyone h ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

Techniques for transferring child properties and values to parent components upon the screen being initialized

Is there a way to pass property values from a child component to a parent component when the react app is first loaded? In my scenario, I have a parent component named app.js that renders a home component containing a JSON component. Initially, upon loadi ...

An issue has arisen in the production environment on AWS EC2 due to a problem with Nodemailer

When using nodemailer with node.js to send emails, I have set up the following configuration: var transporter = nodemailer.createTransport({ service: 'gmail', host: 'smtp.gmail.com', auth: { ...

Troubleshooting: HTTP client post request working with body.set but not with formData.append for sending data to API

I am in the process of updating the UX for an older application with APIs developed in ASP.NET When I make a POST request as shown below, everything works perfectly. The data is received: var APIURL = sessionStorage.getItem('endpoint') + "/ ...

What is the best way to activate multiple events within an overlapping area containing multiple divs at the same

How can I trigger events on same level divs that overlap in different areas? When there are multiple divs overlapping, only one of them gets triggered. Is there a way to trigger events on all overlapped same level divs? Here is an example code snippet: ...

Experimenting with d3 using Node.js, JSDOM, and Jasmine

I am new to Javascript and node.js, and I want to test if a basic bar chart is being rendered in my node.js/d3 application using jasmine. Could someone provide guidance on what steps I need to take? test.js (file that needs testing): var d3 = require(&ap ...

Tips for preventing the overwriting of a JSON object in a React application

I'm trying to compare two JSON objects and identify the differing values in the second JSON object based on a specific key. My goal is to store these mismatched values in a new JSON object. The current issue I'm facing is that when there are mult ...

Implement a Basic Custom Shader on a Cube in Three.js

Struggling with applying a basic custom shader to a cube in Three.js. Whenever I attempt to use the shader, the cube mysteriously vanishes. No issues when using a standard Toon or Lambert Material - cube rotates and behaves as expected. Oddly, Orbit Contr ...

Using Django with Ajax without the need for the JQuery library

Exploring the world of Ajax without jQuery Library has been quite a journey. I recently created a basic view that displays a random number on the screen. After adding a button and invoking the ajax function, I encountered an issue where clicking the button ...