What would be the best approach to resolving the issue with my recursive function that is returning nested arrays of data?

I am working on a recursive function to navigate through an object that resembles a directory structure, and extract the 'file' objects into an array. However, I'm encountering an issue where instead of getting a simple array with the expected objects, I'm ending up with an array of arrays...

At the end of the code snippet, there are console.logs showing:

console.log(findEntry(repAll, '/first')); // ===> [ { name: '/first' }, [] ]
console.log(findEntry(repAll, '/second')); // ===> [ [ { name: '/second' }, { name: '/second' } ] ]

const repAll = { 
    file1: { 
        name: "/first"
    },
    SubDir: { 
        file2: { 
            name: "/second"
        },
        file3: {
            name: "/second"
        }
    } 
};
const req = {};

function findEntry(data, name) {
  let x = [];
    for (const value of Object.values(data)) {
        // Is this a leaf node or a container?
        if (value.name) {
            // Leaf, return it if it's a match
            if (value.name === name) {
                x.push(value);
            }
        } else {
            // Container, look inside it recursively
            const entry = findEntry(value, name);
            x.push(entry);
        }
    }
    return x;
}

console.log('search: /first');
console.log(findEntry(repAll, '/first'));

console.log('search: /second');
console.log(findEntry(repAll, '/second'));

Answer №1

A suggested optimization is to utilize the spread operator when dealing with the result of the findEntry function, rather than just pushing items into an array.

const repAll = { 
    file1: { 
        name: "/first"
    },
    SubDir: { 
        file2: { 
            name: "/second"
        },
        file3: {
            name: "/second"
        }
    } 
};
const req = {};

function findEntry(data, name) {
    let x = [];
    for (const value of Object.values(data)) {
        // Determine if node is a leaf or container
        if (value.name) {
            // Return if leaf matches
            if (value.name === name) {
                x.push(value);
            }
        } else {
            // Recursively search inside containers
            x.push(...findEntry(value, name));
        }
    }
    return x;
}

console.log('search: /first');
console.log(findEntry(repAll, '/first'));

console.log('search: /second');
console.log(findEntry(repAll, '/second'));

Answer №2

Utilizing this method:

function searchItem(data, key,x) {

    for (const val of Object.values(data)) {
        // Check if it's a leaf node or a container
        if (val.key) {
            // Leaf node, match and add to results
            if (val.key === key) {
                x.push(val);
            }
        } else {
            // Container, recursively search inside
            const result = searchItem(val, key,x);
            x.push(result);
        }
    }
    return x;
}

Now use it in the following way :

let arr=[];
console.log(searchItem(allData, '/first',arr));

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

To utilize jQuery Load HTML in Cordova iOS versions equal to or greater than 9.2

My cordova project was functioning perfectly until I upgraded to cordova 6.0 and the new webview, which has now caused this error: XMLHttpRequest cannot load file:///Users/adrian/Library/Developer/CoreSimulator/Devices/3ACC077E-9068-4352-A28B-4BD13124BE5B ...

Merging two arrays within a for-each iteration

$user = $this->get_user_or_redirect(); $calendars = $user->get_calendars1(); $events = []; foreach ($calendars as $calendar) { $events += $calendar->get_events(); } $calendars is an array that ...

Back to top button displayed exclusively on desktop view (not visible on mobile devices)

I managed to create a scroll-to-top button that only appears when the user has scrolled down 25px from the top of the document. I achieved this using JavaScript by following a tutorial, as I am still unfamiliar with this programming language. However, I w ...

Any tips on making the jQuery scrollTop() function function properly?

I'm currently working on a script that triggers a change in text color when the user scrolls to a specific point on my HTML page. Here's what I've managed to put together so far: jQuery(document).ready(function(){ if(jQuery(window).s ...

What is the process for uploading images using the Dropbox API v2 in a Node.js backend environment?

Recently, I've been encountering issues while attempting to upload images to a Dropbox app folder using the Dropbox API v2 within my node.js backend. Unfortunately, every image that successfully uploads seems to be corrupted and ends up being only 15 ...

Can the import path for vuejs app.js be determined dynamically or within an if-else condition?

App.js Updated import x from 'project/a' Is it possible to change it to: var project = 'a' if(project == 'a') { import x from 'project/a' } else { import x from 'project/b' } or would this alterna ...

creating a two-dimensional array in Swift using programming techniques

I am struggling to create a 2d array using a for loop. I have tried using "+=" and .append without success so far. Here is the code I have come up with, please disregard the variable names as they were rushed. let firstThing = contentsOfFile!.componentsSe ...

Display PickerIOS when a button is clicked in a React Native application

I am a beginner with the react framework and I'm trying to implement a PickerIOS component on button click. However, I'm having trouble understanding how to call other classes upon an event. I found this code snippet on the React Native site: v ...

Remove inline CSS from HTML elements

Having a large HTML file structured like this: <div style="min-height: 32px; padding: 5px; width: 800px; margin: 50px auto; overflow: auto; font-size: 12px;" class="selectable clearfix selected_layer" id="wrap"> <div class="selectable" id="l1" st ...

The interval becomes congested due to the execution of two simultaneous Ajax calls

I have an Interval set to run a function every 3 seconds. intervalStepper = window.setInterval('intervalTick()','3000'); function intervalTick() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

Utilizing an Embed tag to play an mp3 file with the source being an ashx file and byte array retrieved from the database

I am currently storing text to speech mp3 files as varbinary(max) in the database. My goal is to play these audio files using the embed tag, where the source is an ashx file that will receive the id of the database record and write the byte array. Here is ...

Loading vue.config.js Asynchronously for Pre-Rendering Meta Data

I am facing an issue with asynchronously loading data in my Vue.js application's config for use with Chris Fritz's PrerenderSPA webpack plugin. It seems that the routes are not being pre-rendered as expected. When I manually input the values, th ...

Transforming an 11x2 grid by identifying distinctive values and assigning new values

I am looking for a function that can process a n*2 input array and generate a n*2 output array, where the first column elements consist of unique values from the first column of the input array, and the second column elements are sums of numbers correspond ...

Filtering Out Results by Date Range in SQL for Microsoft Access

In my database, I have a collection of pathology results from various patients. Oftentimes, there are multiple samples taken for the same patient over different dates. My goal is to retain the initial record for each patient, while disregarding any subsequ ...

What are some solutions for troubleshooting setInterval issues?

I have a h1 element with a v-for loop that displays items from my array in the following format: <h1 v-for="(record, index) of filteredRecords" :key="index" :record="record" :class="get ...

Scrolling through a single jQuery page with embedded links to navigate to other pages

My website features a single-page layout with menu links that scroll down the page using div IDs as anchors (e.g. www.mydomain.com/#div-id). However, I also have some external pages linked in the header. The problem arises when I am on one of these extern ...

Storing array information in MongoDB with Rails

I am facing an issue with data insertion in MongoDB using Rails, specifically when the data type is an array. Here is the code snippet: def friend Twitter.configure do |config| config.consumer_key = 'GpCZ3ppx2tvOYB7mP4FONw' config.consumer_sec ...

Working with nested JSONArrays in Android

Looking at the json data snippet below: "categories": [ [ "Belgian Restaurant", "belgian" ], [ "Brasserie", "brasseries" ] ], I am trying to extract information from the second JSONArray (in thi ...

Error: The attempt to access the 'useContext' property of null has failed due to a TypeError

Nowhere in my React code am I using the useContext property. There is a compiled webpack file in an npm package with a component inside. When trying to use this component in my React app, it throws an error: Uncaught TypeError: Cannot read properties of nu ...

Utilize the HTML File Selector to access files from the server side

Is there a way to use the HTML file selector <input type="file"> to browse files that are stored on my server rather than locally? I understand that JS is client-side, and despite researching different approaches, I have not come across any suitable ...