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

Trouble with saving the positioning after drag and drop

I am currently facing an issue with my drag-and-drop script where the coordinates of positioned relative divs are not being saved in the same position when I reload. These divs are contained within a container with specific height and width, restricting t ...

Putting AngularJS controller through its paces using Jasmine

Here is the code for my NewPageCtrl.js file: angular.module('NewPageCtrl', []).controller('NewPageController', function($scope, $document) { $scope.showMe = false; }); And here is the content of test.js: describe('NewPageC ...

JSON.NET parsing data without corresponding field names

While working on a VB.NET forms application and utilizing JSON.NET, I am fetching data from a third-party source in the form of simplified JSON displayed below. { "Venue": { "ID": "ABDDF", "Name": "My Place", "Address": { "Address1": " ...

Select2 isn't functioning properly, consistently showing the message "No results found" every time

After exhausting all options on this platform without success, my goal remains unchanged: to extract state data from a JSON file generated by a servlet and then present the information in a dropdown menu using AJAX. However, no matter what I input into th ...

Converting a JSONObject to a JSONArray on Android is not possible

My android code below is producing an error: org.json.JSONException: Value {"ID":1,"DisplayName":"Manish","UserName":"[email protected]"} at AuthenticateUserResult of type org.json.JSONObject cannot be converted to JSONArray The code snippet is a ...

Interface-derived properties

One of the challenges I'm facing is dealing with a time interval encapsulation interface in TypeScript: export interface TimeBased { start_time: Date; end_time: Date; duration_in_hours: number; } To implement this interface, I've created ...

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

In JavaScript, escape is comparable to android decode

I used a JavaScript method to encode a string: var result = escape('Вася') The resultant string is: "%u0412%u0430%u0441%u044F" Now I need to decode this string in Java. How can I achieve this? The following attempt did not work: URLDecod ...

Activating a button by pressing the Enter key using JQuery

$("#AddDataStavka, #AddDataRazmer").on("keyup", function (event) { if (event.keyCode == 13) { e.preventDefault(); $("tr.trNewLine").children().first().children().first().get(0).click(); } }); /* I'm trying to execute this ...

On startup of the chrome app, read and load a JSON file into a variable

As I develop a chrome app, my goal is to store all configuration defaults in json file(s) alongside other assets. I am currently using AJAX requests to load them, but I'm wondering if there is a more efficient way to handle this. Is there perhaps an o ...

Is there a way to simulate the parameters of a method callback from an external dependency in Nodejs

Imagine a scenario where I have the following structure: lib/modules/module1.js var m2 = require('module2'); module.exports = function(){ return { // ... get: function(cb){ m2.someMethod(params, function(error, ...

Using Bootstrap4 to merge rows into a single column or apply rowspan in Bootstrap

Hey there, I have a specific requirement that I need help with. Check out the image here. I want to enable the LCM information box when the LCM checkbox is checked. Below is my code: <div class="panel-body "> <div class="c ...

Angular and AngularJS directives work together to indicate events on a line chart

Currently, I am creating a dashboard using AngularJS along with Angularjs-nvd3-directives, mainly focusing on line charts. I am interested in adding markers to the chart for specific events. For instance, if I have a time series data, I want to be able to ...

How can I ensure that my text input and button are in sync in ReactJS?

I'm currently developing a basic search bar that reads input and updates the 'inputString' state when the content changes. Upon clicking the 'search' button, the inputString is split and assigned to the 'keywords' state a ...

Obtain the response header variable within a Shiny application

In Apache, the LDAP login is passed to a variable called X-Remote-User in the header: I am unsure how to retrieve this information in my Shiny app. Does anyone have any ideas? Maybe using JavaScript could be a solution? ...

What is the designated destination for JWT Tokens?

For my user login/signup process, I'm utilizing JWT and have a query regarding how the token is transmitted. At present, I am saving the token as a property in a JSON object on the server side, then passing it to the front-end. Upon receiving the obj ...

Could one potentially generate new static files in Nextjs without needing to rebuild the entire app?

After recently beginning to utilize NextJs' getStaticProps feature, I have found that the static files generated at build time are quite impressive. However, my content is not static and requires updates without having to rebuild the entire app each t ...

The issue of Ajax failing to send POST variables to a specified URL

I'm looking to dynamically populate related dropdowns with data fetched from the database. On my HTML page, I have a select element with the id 'fontes' and another one with the id 'cargos'. Below is the jQuery code snippet that I ...

Is it possible to validate a template-driven form without using the model-driven approach?

Attempting to validate a template-driven form in Angular without two-way data binding has proved to be challenging. I have successfully implemented validation using [(ngModel)], but running into an error when trying to validate the form without the MODEL p ...

Send your information to a JSONP endpoint

Can data be posted to JsonP instead of passing it in the querystring as a GET request? I have a large amount of data that needs to be sent to a cross-domain service, and sending it via the querystring is not feasible due to its size. What other alternati ...