What is the process for writing code in a recursive manner?

I'm in the process of converting these code snippets into smaller ones using recursion. However, I've hit a roadblock while trying to implement a for loop.

The dictionary I am working with is: var structure = []; and it has the following structure:

"path": path,
"children": []

I am populating this dictionary by parsing a JSON file. One of the paths from the JSON file looks like this: "path": "Assignment_1/src/com",. To rebuild this structure within my structure dictionary, I split the path using `/` and attempt to fill in the necessary parts. The first part, "path": "Assignment_1/",, goes into the main structure. The subsequent parts, such as "path": "Assignment_1/src/",, get inserted into the respective children dictionaries.

Here's how I'm currently achieving this without using recursion:

if(path.split("/").length == 2) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    structure[j]["children"].push({
                        "path": path1,
                        "children": []
                    })
                }
            }
        }
    }

    if(path.split("/").length == 3) {
        if(type == "tree") {
            var path0 = path.split("/")[0];
            var path1 = path.split("/")[1];
            var path2 = path.split("/")[2];

            for(var j = 0; j < structure.length; j++) {
                var foundPath = structure[j]["path"];

                if(foundPath == path0) {
                    for(var k = 0; k < structure[j]["children"].length; k++) {
                        var foundPath = structure[j]["children"][k]["path"];

                        if(foundPath == path1) {
                            structure[j]["children"][k]["children"].push({
                                "path": path2,
                                "children": []
                            })
                        }
                    }
                }

                print(structure);
            }
        }
    }

Now, I aim to streamline this process so that it automatically traverses all folders and populates my structure dictionary. I initially experimented with while loops, but encountered challenges with these statements:

structure[j]["children"].push({ })
structure[j]["children"][k]["children"].push({ })

These sections proved to be complex to program. Any assistance or guidance on simplifying this would be greatly appreciated!

UPDATE

Input (a part of it):

{
  "path": "Folder_1/src/com",
  "mode": "040000",
  "type": "tree"
},

Output:

https://i.stack.imgur.com/RqOCg.png

Answer №1

let inputData = [
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_1/src/com",
      "mode": "040000",
      "type":"tree"
    },
    {
      "path": "Folder_2/docs/files",
      "mode": "040000",
      "type":"tree"
    }   
],
outputData = [];

inputData.forEach( function( data ) {
    processData( data.path.split('/'), outputData );
} );

function processData( data, into ){
    let splitData = data,
      firstData = splitData.shift(),
      newDataItem = { 'src': firstData, 'children': [] };     

    if( splitData.length ){
        processData( splitData, newDataItem.children );   
    }   
  if( ! into.find(function(item){return item.src == firstData } ) ){
        into.push( newDataItem );
  }
}

console.log( outputData );

Link to JSFiddle Demo

Keep in mind that the code currently does not consider the condition where type == tree, whatever that means.

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

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Comparing JSON strings

In the midst of a C++ project, I find myself struggling to compare multiple JSON strings that are passed as arguments in a function. The goal is to return a boolean based on their comparison. While using Jsoncpp for this task, I've encountered challen ...

Dealing with errors while managing asynchronous middleware in Express

I have implemented an asynchronous middleware in express to utilize await for a cleaner code structure. const express = require('express'); const app = express(); app.use(async(req, res, next) => { await authenticate(req); next(); }) ...

Is there a way to customize the animation for a button in material UI?

Trying to implement material UI in React and looking for a button that does not have the standard wave animation effect upon clicking, which you can see demonstrated here. Instead, I am searching for an animation that instantly fills the entire button wit ...

When I upgraded my "react-router-dom" from version "5.2.0" to "6.14.0", I encountered a warning stating "No routes matched location"

After updating react-router-dom from version "5.2.0" to "6.14.0", I encountered a warning saying "No routes matched location." Initially, I received an error stating that "<Route> is only meant to be used as a child of <Routes>, not rendered d ...

Updating the id token in VueJs using Axios interceptor when it expires

I need to implement an axios interceptor that will add the idToken as an authorization header to every axios call, and also refresh the idToken if it has expired before making any call. My current code for this task is as follows: axios.interceptors.requ ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

What is the best way to swap out an icon based on the chosen option?

Here is my code: $('#mySelect').on('change', function() { var value = $(this).val(); $(".title").html(value); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href=" ...

What are some ways to troubleshoot the UI of a Nativescript app?

As a newcomer to NativeScript technology, I often encounter challenges while developing applications. Whether it's troubleshooting why a textview is not displaying properly, identifying layout overlaps, or detecting other distortions in the UI, debugg ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

difficulty receiving the information promptly via an AJAX request (utilizing AJAX and the 'for' loop)

Currently, I am successfully retrieving data from an ajax call for individuals. However, my next task is to retrieve multiple sets of data simultaneously. Here is the code snippet: for(var i = 1; i <= 2; i++){ console.log(i); $.ajax({ url: cal ...

Using AngularJS to display multiple objects in the same ng-repeat loop

Is it possible to display two objects simultaneously in ng-repeat? <tr data-ng-repeat="target in targets |session in sessions |filter:query | orderBy:orderProp"> ...

Node.js tutorial: Building routes with regex and implementing redirects

Can anyone provide guidance on how to utilize route and redirect URLs with parameters in Node.js using Express? If the URL is xyz/?s=test, it should redirect to indexRouter. If the URL is xyz/, it should also redirect to indexRouter. I'm facing issu ...

Learn the process of utilizing JavaScript/Node.js to dynamically upload images onto a webpage directly from a database

Currently, I am developing a web application and building a user profile page where I aim to showcase user information along with a profile picture. Working with node/express/jade stack, I have a javascript file that manages loading the appropriate jade vi ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Check if the page has been loaded using Jquery

Can anyone share a helpful strategy for initiating a function in JavaScript that only begins once the entire page has finished loading? ...