Implementing a search functionality with a multi-level array filter

I am currently working on integrating search functionality with a multilevel array.

Let's suppose I have the following JSON multilevel array:

const data = [
        {
            menu: 'Example',
            submenu: [
                {
                    menu: 'Example1',
                },
                {
                    menu: 'Example2',
                    submenu: [
                        {
                            menu: 'Example2.1',
                        },
                        {
                            menu: 'Example2.2',
                        },
                        {
                            menu: 'Example2.3',
                        },
                    ],
                },
            {
        menu: 'NewTest',
        submenu: [
            {
                menu: 'NewTest1.1',
            },
            {
                menu: 'NewTest1.2'
            },
            {
                menu: 'NewTest1.3',
            },
        ],
    },
            ],
        }]

If I enter "Example2.3" in the search box, I would like the JSON to be formatted as follows:

const data = [
        {
            menu: 'Example',
            submenu: [

                {
                    menu: 'Example2',
                    submenu: [
                        {
                            menu: 'Example2.3'
                        },
                    ],
                },
            ],
        }]

I came across an article at Using array.filter down multiple levels but it did not provide the desired output. It returned all the submenu items instead.

const data = [
        {
            menu: 'Example',
            submenu: [
                {
                    menu: 'Example1',
                },
                {
                    menu: 'Example2',
                    submenu: [
                        {
                            menu: 'Example2.1',
                        },
                        {
                            menu: 'Example2.2',
                        },
                        {
                            menu: 'Example2.3',
                        },
                    ],
                },
            ],
        }]

Is there another approach that can help me achieve my desired result? Thank you in advance

Answer №1

If you're looking to filter out sub menu elements based on a specific target value, one efficient way to achieve this is by using a recursive approach alongside the reduce method. This method helps in returning only those submenu elements that match the target value while excluding the others.

const data = [{"menu":"Test","submenu":[{"menu":"Test1"},{"menu":"Test2","submenu":[{"menu":"Test2.1"},{"menu":"Test2.2"},{"menu":"Test2.3"}]},{"menu":"TestNew","submenu":[{"menu":"TestNew1.1"},{"menu":"TestNew1.2"},{"menu":"TestNew1.3"}]}]

function search(data, value) {
  return data.reduce((r, e) => {
    const object = { ...e }
    const result = search(e.submenu || [], value)
    if (result.length) object.submenu = result
    if (e.menu == value || result.length) r.push(object)
    return r;
  }, [])
}

console.log(search(data, 'Test2.1'))
console.log(search(data, 'TestNew1.3'))

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

Incorporating a new data series into your candlestick chart with Highstock

I've encountered an issue with adding a data series to my candlestick chart in Highstock using Highcharts. Here's the script I'm using: $.ajax({ url : 'indicator', type : 'GET', data ...

The lifecycle of a React state in a filtering component

Seeking guidance on handling state updates in a component designed for filtering purposes (such as selecting dates, min/max values, etc). My current setup is as follows: onMinDateChange(minDate) { this.setState({minDate}); }, onMaxDateChange(maxDate) ...

Node.js unable to verify RSA-PSS signature due to validation issues

I currently have a JavaScript client and a Node.JS server setup. My goal is to sign a basic text on the client side, send the signature along with the publicKey to the server, and have the server verify the publicKey. Everything seems to work fine on the ...

What steps can be taken to prevent double division within a loop?

Appreciate your assistance. This is the structure of my code: var CatItems = ""; for(var x=0; x < data.PRODUCTS.length; x++) { if (x % 3 === 0) CatItems += '<li class="jcarousel-item jcarousel-item-horizontal jcarousel-item-'+[x]+' ...

The use of JSON within an array in JavaScript and Ajax

My expertise lies in JavaScript (Ajax): function processSportAndLeagueDetails() { var url = 'http://localhost:8012/football/football/public/admin/ajax/'; var teamId = document.getElementById('team_a_id').value; var reques ...

Sorting an array of pointers to different arrays using bubble sort within a C function

I'm facing an issue with my bubble sort function for an array of pointers, where each pointer points to another array. The error message I receive indicates a violation of the writing location (Visual Studio). To clarify, I use (*parr)++ because the ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Attempting to share a two-dimensional array globally across two C++ class files

I'm currently developing a game in C++ and I've encountered a situation where I need to share a 2D array globally across multiple class files. Here's a simplified version of my code: // This is the first file that initializes and populates ...

What are some strategies for safeguarding a disabled button?

Is there a way to securely disable a button if the user does not have permission to access it? I currently disable it at the Page_Load event: Page_Load() { if(!userhasrights) { btn.Enabled=false; } } However, after rendering, ASP.N ...

Trigger Google Analytics event when file is downloaded from server

Here is a helpful resource on sending events to Google Analytics via API server sided: Send event to Google Analytics using API server sided An email containing a download link has been sent to a customer: Hello, Please access your product through thi ...

Finding the ID associated with a label

I'm currently working on a project and I require the ID of the label in order to store it and display it within a modal that will be shown to the user. How can I retrieve the ID instead of the name that is enclosed within the tags? window.saveAndDisp ...

How to retrieve the value from a JSON object when the key is unknown in JavaScript

Here is the JSON file I'm working with: { "status": 200, "msg": "OK", "result": { "files": { "count": 1, "pUnJbKzql0f2": { "name": "How ...

Alert popup onclick feature is malfunctioning

SOLVED: I finally figured out the issue and it is now working perfectly. I had to manually switch to Chrome instead of using the Brackets live viewer. I want an alert box to pop up when the "Home" link is clicked on my website. I tried creating a separate ...

Retrieving Files using Ajax Across Different File Types

I recently came across the following code snippet: DOM_imgDir = "img/UI/DOM/"; fileextension = ".jpg"; $.ajax({ url: DOM_imgDir, success: function (data) { $(data).find("a:contains(" + fileextension + ")").each(function () { filename = thi ...

Dynamic Node.js server constantly updating

My goal is to create a dynamic Node.js Express server that updates live, possibly by creating a specific route like /update to load a new configuration file. My concern is that the server could be in any state when the update occurs. It's possible tha ...

Issue with Reactjs not triggering the onChange callback in the child component

I created a reusable input component specifically for URLs. If a URL does not start with 'http', this component automatically adds it to the beginning. Here is the code for the component: import React, {useContext, useCallback} from 'react& ...

The JSONP method, utilizing .getJSON, is resulting in an undefined response

I'm currently experimenting with a task from Learning jQuery 4th edition by Karl Swedburg that involves Ajax, particularly JSONP. Here's the code I am using: $(document).ready(function(){ var url='https://api.github.com/users/jquery/repos& ...

continuously replacing keywords with hyperlinks occurs an endless number of times

Struggling to insert hyperlinks around specific keywords without endless replacements occurring: var replacements = [ { txt: 'magicFunction', link: 'https://www.example.com/doc/api/magicFunction.htm' }, ]; $(function() { $.each( ...

Determining if a value matches any element within an array in MATLAB

Is there a way in MATLAB to determine if a specific value is equal to any value contained within a different array? I want to use this to compare whether an index in one matrix matches any of the values stored in another array (where the stored values are ...

Is it possible to convert a blob to an image file using the FileReader in HTML

client side code <head> <script> var reader = new FileReader(); var objVal; var image = new Image(); reader.onload = function(e) { document.getElementById('propertyImg').setAttribute('src', e.target.result); }; fun ...