What is the best approach for filtering a nested array in this scenario?

Here is the response I am getting:

 let m =  [
      {
        name: 'Summary',
        subListExpanded: false,
        subList: [
        ]
      },
      {
        name: 'Upload',
        subListExpanded: false,
        subList: [
        ]
      },
      {
        name: 'Tasks',
        subListExpanded: false,
        subList: [
        ]
      },
      {
        name: 'Dashboard',
        subListExpanded: false,
        subList: [
        ]
      },
      {
        name: 'Master',
        subListExpanded: false,
        subList: [
          {
            id: 'user-master',
            name: 'User-Master'
          },
          {
            id: 'menu-master',
            name: 'Menu-Master'
          },
          {
            id: 'entity-master',
            name: 'Entity-Master'
          },
          {
            id: 'vendor-master',
            name: 'Vendor-Master'
          },
          {
            id: 'xxx-master',
            name: 'xxx-Master'
          }
        ]
      }
    ];

If I search for m, the filtered result should look like this:

 [
  {
    name: 'Summary',
    subListExpanded: false,
    subList: [
    ]
  },
  {
    name: 'Master',
    subListExpanded: false,
    subList: [
      {
        id: 'user-master',
        name: 'User-Master'
      },
      {
        id: 'menu-master',
        name: 'Menu-Master'
      },
      {
        id: 'entity-master',
        name: 'Entity-Master'
      },
      {
        id: 'vendor-master',
        name: 'Vendor-Master'
      },
      {
        id: 'xxx-master',
        name: 'xxx-Master'
      }
    ]
  }
];

If I search for master, the filter response should be as follows:

[
      {
        name: 'Master',
        subListExpanded: false,
        subList: [
          {
            id: 'user-master',
            name: 'User-Master'
          },
          {
            id: 'menu-master',
            name: 'Menu-Master'
          },
          {
            id: 'entity-master',
            name: 'Entity-Master'
          },
          {
            id: 'vendor-master',
            name: 'Vendor-Master'
          },
          {
            id: 'xxx-master',
            name: 'xxx-Master'
          }
        ]
      }
    ];

If I search for xxx-master, the filter response will be:

[
{
        name: 'Master',
        subListExpanded: false,
        subList: [
          {
            id: 'xxx-master',
            name: 'xxx-Master'
          }
        ]
      }
    ];

If I search for slkvcsmcskc, the filter response will be:

 []

My TypeScript code is not functioning correctly. Can you assist me in resolving this issue?

  m.filter(x=> x.name.toLowerCase() === search.toLowerCase() || x.subList.some(x1=> x1.name.toLowerCase()===search.toLowerCase()))

Answer №1

The code snippet below demonstrates the functionality you are looking for. It includes additional complexity that might not be necessary for your specific scenario. Nevertheless, this example is designed to handle lists with multiple levels of nesting (as shown in the 'bar' example).

let data =  [
      {
        name: 'Summary',
        subListExpanded: false,
        subList: [
        ]
      },
      {
        name: 'Upload',
        subListExpanded: false,
        subList: [
          {
            name: 'foo',
            subList: [
              {
                name: 'bar',
              }
            ],
          }
        ]
      },
      {
        name: 'Tasks',
        subListExpanded: false,
        subList: [
        ]
      },
      {
        name: 'Dashboard',
        subListExpanded: false,
        subList: [
        ]
      },
      {
        name: 'Master',
        subListExpanded: false,
        subList: [
          {
            id: 'user-master',
            name: 'User-Master'
          },
          {
            id: 'menu-master',
            name: 'Menu-Master'
          },
          {
            id: 'entity-master',
            name: 'Entity-Master'
          },
          {
            id: 'vendor-master',
            name: 'Vendor-Master'
          },
          {
            id: 'xxx-master',
            name: 'xxx-Master'
          }
        ]
      }
    ];
    
    
function customSearch (input, query) {
  const queryRegEx = new RegExp(query, 'i');
  
  function internalSearch (data) {
    let resultArr = [];

    data.forEach(item => {
      const parentMatch = queryRegEx.test(item.name);
      let subMatchFound = false;
   
      if (item.subList) {
        let subResultArray = internalSearch(item.subList);
        subMatchFound = subResultArray.length > 0;

        item.subList = subMatchFound ? subResultArray : [];
      }
      
      // Add parent item to result array if it matches the query or any child items match
      if (parentMatch || subMatchFound) resultArr.push(item);
    });
    
    return resultArr;
  }
  
  return internalSearch(JSON.parse(JSON.stringify(input)) /* create a clone using JSON.parse(...) */);
}

console.log('master', customSearch(data, 'master'));
console.log('xxx-master', customSearch(data, 'xxx-master'));
console.log('m', customSearch(data, 'm'));
console.log('bar', customSearch(data, 'bar'));
console.log('slkvcsmcskc', customSearch(data, 'slkvcsmcskc'));

Answer №2

It is important to note that the correct structure should be as follows:

obj = {
    _id: "sjkd9skj",
    data: {
      dektop: [
                { 
                   x: 2,
                   y: 3,
                   t: { key: 'aabbcc'}
                }, 
                ... 
              ],
      mobile: [
                { 
                   x: 4,
                   y: 3,
                   t: { key: 'ffff'}
                }, 
                ... 
              ],
      print: [
                { 
                   x: 7,
                   y: 5,
                   t: { key: 'ppp'}
                }, 
                ... 
              ]
    }
}

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

Retrieve a zip file using React and Node from a RESTful API

I have an application built with React and Node where I have a table that includes a download button. Clicking the download button triggers a request to my Node app, which in turn should call a REST API to download a zip file directly into the browser. In ...

nodemon was not properly installed on the system

I attempted to add nodemon to my application using the command below: npm install nodemon -g This is the output that was generated: changed 116 packages, and audited 117 packages in 8s 16 packages are looking for funding run `npm fund` for details fou ...

Can I obtain a dictionary containing the connections between labels and phrases from the classifier?

I've implemented a LogisticRegressionClassifier using the natural library for node: const natural = require('natural'); const classifier = new natural.LogisticRegressionClassifier(); classifier.addDocument('category1', 'sent ...

Unable to iterate through a collection of items

Struggling to incorporate the worklog JSON fields into an array using Python because I can't seem to loop over an array in Python. Take a look at the code snippet below: try: worklogs_to_insert = [] for i in issue.fields.worklog["worklogs"]: ...

Is it possible for javascript to show the user's current location on a google map without using a KML layer?

I need help with loading a KML file using JavaScript and adding a marker to the map at the user's current location. The code I have been working on works fine, but it seems to be missing the geolocation check for the current position. How can I proper ...

Utilize JQuery to Extract HTML Elements

I'm working on developing a Chrome extension and one of my tasks is to extract specific text from the webpage I am currently visiting and store it in a variable. I have been attempting to achieve this using jQuery, however, none of the solutions I&apo ...

Communication between an iOS application and a server

As I am currently developing an iOS app that requires a remote interactive server, I need to send queries and post data to the server. What would be the best approach for this task - using REST, JSON, or SOAP? Are there any tutorials or documentation ava ...

Issue with Backbone collection not being updated despite making a JSONP request

Recently, I delved into the world of Backbone.js and currently, I am immersed in developing an app using Brunch that makes a JSONP request to an external API for populating my collection and models. Despite following guidance from previous posts (here and ...

Ways to display notifications when the user is not actively browsing the website?

How can websites display notifications even when the user is not actively on the site? Take Facebook messenger, for instance. Even with the page closed, notifications still pop up. The same goes for Twitter, which also sends push notifications. I ...

The issue of Access-Control-Allow-Origin restriction arises specifically when using the gmap elevation API

My attempts to retrieve the elevation of a site using latitude and longitude have been unsuccessful due to an error I encountered while making an ajax call. Regardless of whether I use HTTP or HTTPS, I receive the following error message: "No 'Access ...

Does the method in the superclass "not exist" within this type....?

Our TS application utilizes a JavaScript library, for which we crafted a .d.ts file to integrate it with TypeScript. Initially, the file resided in a "typings" directory within the project and everything operated smoothly. Subsequently, we opted to relocat ...

Steps to transform a JSON string into a struct

Recently, I started working with golang and I've been struggling to parse a JSON string into a struct. Here is the JSON String: dailies":[{"userAccessToken":"acessToken","uploadStartTimeInSeconds":1499744832,"uploadEndTimeInSeconds":1499744832,"ca ...

Guide on transforming a collection of files from formdata into a JavaScript object

I have a dataset containing multiple images associated with the same product id. import client from "@/lib/fetchWrapper"; export default async function addProductImage({ photo, productId, }: { photo: File[]; productId: string; }) { if ...

organizing a List<Object> both numerically and alphabetically by the field 'product' in the Object

List<ShipInventoryReportDataVO> lstShipInvData = shipInventoryReportDAO .getShippableInventoryReportData(inputVO, true); ShipInventoryReportDataVO represents my object class and retrieves data from a stored procedure. Within the ShipInventoryRep ...

How can I remove the outline when focusing with the mouse, but still retain it when focusing with the

Is there a way in JavaScript to detect if an element received focus from the keyboard or mouse? I only want the outline to show when it's via the keyboard, not the mouse. If this is possible, how can I override the browser's default outlining be ...

I'm having trouble locating my route for some unknown reason

I've set up a basic code structure to test my routes, but I keep getting a 404 error. Although I have an app.all function to catch errors, I'm having trouble pinpointing where the issue lies. Below is my index.js file, where I've configured ...

Slow rendering occurs with unthrottled range input, even with proper throttling applied

I'm currently seeking some general guidelines because I'm unsure where to turn for help at the moment. The issue I am facing involves an uncontrolled input[type=range] slider that performs very slowly when there are numerous steps (works fine wi ...

Evaluating the functionality of a React JS dropdown using Selenium automation and Java

Could you please advise me on how to select a value from a dynamically populated dropdown using React JS? An example would be greatly appreciated. Below is the HTML code snippet for the page... The division that contains the label "Year" functions as ...

Questions on how to utilize ES6 Express and static methods

Recently, I've been working with Express and wanted to incorporate ES6 using babel in my project. One question that has been on my mind is related to the use of static methods for handling requests, as shown below: class MyCtrl { static index (r ...

Leverage ngFor to loop through a "highly intricate" data structure

In my project, I have stored data in a JSON file structured as follows: { "name": { "source1": ____, "source2": ____, "source3": ____ }, "xcoord": { "source1": ____, "source2": ____, "source3": _ ...