Utilize the onChangeText function in React Native to filter out each individual value within a nested array

I currently have an array with nested children in it, where the children can range from one to multiple values. I am working on implementing a local filter within my component. Whenever a user types anything into the textInput, the application will display suggestions based on the word typed by the user. These suggestions will be sourced from my pre-defined array.

Below is the code I am currently using:

export function onSearch(categoryList, searchText) {
    var searchList = [];
    return function(dispatch) {
       categoryList.map((item, i) => {
           if (item.title.includes(searchText)) {
             searchList.push(item);
           }
       });
       dispatch({
         type: types.Search_Success,
         payload: searchList
       });
    };
}

In the above method, you can see that the code will filter values up to the parent level only. Therefore, I tried to add code by including conditions like this:

if(item.children.length > 0){
    item.children.map((item, i) => {
        if (item.title.includes(searchText)) {
            searchList.push(item);
        }
    });
}

However, the issue arises when I have many children as I cannot include such conditions inside the code.

Here is an example of how my array is structured:

[{
    "id": "38",
    "title": "What's New",
    "url": "what-is-new"
}, {
    "id": "20",
    "title": "Women",
    "url": "women",
    "children": [{
        "id": "21",
        "title": "Tops",
        "url": "tops-women",
        "children": [{
            "id": "23",
            "title": "Jackets",
            "url": "jackets-women"
        }, {
            "id": "24",
            "title": "Hoodies & Sweatshirts",
            "url": "hoodies-and-sweatshirts-women"
        }, {
            "id": "25",
            "title": "Tees",
            "url": "tees-women"
        }, {
            "id": "26",
            "title": "Bras & Tanks",
            "url": "tanks-women"
        }]
    }, {
        "id": "22",
        "title": "Bottoms",
        "url": "bottoms-women",
        "children": [{
            "id": "27",
            "title": "Pants",
            "url": "pants-women"
        }, {
            "id": "28",
            "title": "Shorts",
            "url": "shorts-women"
        }]
    }]
}, {
    "id": "11",
    "title": "Men",
    "url": "men",
    "children": [{
        "id": "12",
        "title": "Tops",
        "url": "tops-men",
        "children": [{
            "id": "14",
            "title": "Jackets",
            "url": "jackets-men"
        }, {
            "id": "15",
            "title": "Hoodies & Sweatshirts",
            "url": "hoodies-and-sweatshirts-men"
        }, {
            "id": "16",
            "title": "Tees",
            "url": "tees-men"
        }, {
            "id": "17",
            "title": "Tanks",
            "url": "tanks-men"
        }]
    }, {
        "id": "13",
        "title": "Bottoms",
        "url": "bottoms-men",
        "children": [{
            "id": "18",
            "title": "Pants",
            "url": "pants-men"
        }, {
            "id": "19",
            "title": "Shorts",
            "url": "shorts-men"
        }]
    }]
}]

What I aim for is that when I type "m", it should show all titles containing the letter "m".

Please inform me if my question is unclear.

Regards

Answer №1

One possible solution for your problem is to create a recursive function that can effectively handle it. Here's an example of how you could implement this:

const findMatches = (categories, searchTerm) => {
  return dispatch => {
    const matches = [];

    const addToMatches = category => {
      if (category.title.includes(searchTerm)) {
        matches.push(category);
      }
      if (category.children) {
        category.children.forEach(addToMatches);
      }
    };

    categories.forEach(addToMatches);

    dispatch({
      type: types.Match_Found,
      payload: matches
    });
  };
};

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

Ways to retrieve data object within an HTMLElement without relying on jQuery

Within my web application, I have successfully linked a jQuery keyboard to a textbox. Now, I am seeking a way to explicitly call the keyboard.close() function on the keyboard as I am removing all eventListeners from the text field early on. To achieve thi ...

How do you trim a string and display the final 3 characters?

When dealing with a list of objects, I want to ensure that the chain of tasks does not become too long and break the table or appear aesthetically unpleasing. Therefore, my goal is to trim the tasks and display only the last 3. In the image below, multiple ...

"Maximizing User Experience with Single Page Applications and RESTful APIs

Utilizing hypermedia is crucial for a truly RESTful API, as it allows clients to navigate through the application using dynamic hyperlinks provided by the server (also known as HATEOAS). While this concept works well for web applications, how can it be ap ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Modifying the height of the bar in Google Charts Timeline using react-google-charts

I am currently working on a Google Chart timeline using react-google-charts. <Chart chartType="Timeline" data={data} width="100%" options={{ allowHtml: true bar: { groupWidth: 10 }, }} ...

In JavaScript, what do we call the paradigm where a variable equals a variable equals a function? Let's take

Feeling a bit overloaded at the moment, so forgive me if this question seems too simple. I managed to accidentally write some code in Jest for testing a Vue application that actually works: const updateMethod = wrapper.vm.updateMethod = jest.fn() expect(u ...

Adding colors dynamically upon page reload with javascript and jQuery

I have created an array of colors and am attempting to use colors.forEach inside the ready function to call addBox for each color in the array. My goal is to ensure that all the colors are added when the page is reloaded. Please let me know if you require ...

What's the best way to retrieve the id or index of a card within a list?

Struggling to fetch the id's of documents retrieved from a MongoDB database and displayed on React and Material-Ui cards. Tried logging id in functions and APIs, but receiving 'undefined' or metadata from the delete function. Delete functi ...

Angular's route resolve feature does not wait for the promise to resolve before

I just started using angular and I'm facing an issue with my user route. I'm trying to resolve the user object before rendering the view, but even after injecting $q and deferring the promise, the view is loading before the promise gets returned. ...

Obtain the latitude and longitude data in JSON format by utilizing Google Maps' auto-complete feature with AngularJS

What is the method for retrieving latitude and longitude in JSON format from Google Maps autocomplete using AngularJS? ...

I am looking to obtain assistance through denomongo for guidance

The deno-mongo guide page on GitHub is no longer functional. You can find the page here: 'https://github.com/manyuanrong/deno_mongo' I am struggling to understand how to use the plugin and get it up and running. Following the example in the "Re ...

Implementing dynamic data filtering in Vue.js is a valuable feature that

I'm working on a Vuejs project where I need to filter out only the questions with reviewed:true and get the count of them. However, I'm encountering an error while using the code below: TypeError: question.reviewed.includes is not a function. Can ...

The utilization of awaitZip while developing with Express is overlooked by Node.js

I am working on a task to retrieve icon PNGs from gridfs in our mongodb database using mongoose. These icons need to be compressed into a zip file and served at a specific endpoint. Here is the code I have so far: var zip = require("node-native-zip"); as ...

What is the best way to display a segment of an SVG on a Canvas element?

Main Issue: The main objective here is to display a specific part of an SVG image on a fixed size Canvas element within a web page. Approach I Tried: After considering various options, such as using CanVG, I thought about utilizing the viewBox attribute ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

Utilize jQuery to create a dynamic image swapping and div showing/hiding feature

I'm having trouble implementing a toggle functionality for an image and another div simultaneously. Currently, when the image is clicked, it switches to display the other div, but clicking again does not switch it back. Can someone please advise on wh ...

Retrieve data from two separate files and store it as a two-dimensional array in JavaScript

Is there a way to read and convert two .txt files into a 2d array? I currently have a code snippet that looks like this : var fs = require('fs') file = './text1.txt' fs.readFile(file,'utf-8', (e,d) => { textByLine = d.s ...

Issue with toggleClass not functioning properly after receiving data from an AJAX call

On my website, I have a link that triggers an AJAX request. However, when the response comes back and I try to use the toggleClass function in the following .js code snippet, it doesn't work as expected: $(document).ready(function(){ $("td").click( ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

Retrieving information from a function within a Node module

Struggling to get data returned from a function in my Node module. I've researched and read but can't seem to crack it. Using the request plugin to fetch JSON data from an API and aiming to pass that data back for use. Below is my module code: ...