Generate a folder structure based on the Delta data provided by the Dropbox API utilizing the file paths

I came across a query on how to convert a file path into a treeview, and I'm uncertain about achieving the desired outcome using JavaScript:

My goal is to transform an array of paths into a JSON tree structure:

 var paths = [
        "/org/openbmc/UserManager/Group",
        "/org/stackExchange/StackOverflow",
        "/org/stackExchange/StackOverflow/Meta",
        "/org/stackExchange/Programmers",
        "/org/stackExchange/Philosophy",
        "/org/stackExchange/Religion/Christianity",
        "/org/openbmc/records/events",
        "/org/stackExchange/Religion/Hinduism",
        "/org/openbmc/HostServices",
        "/org/openbmc/UserManager/Users",
        "/org/openbmc/records/transactions",
        "/org/stackExchange/Religion/Islam",
        "/org/openbmc/UserManager/Groups",
        "/org/openbmc/NetworkManager/Interface"
    ];

The expected JSON structure based on the folder paths should look like this:

        var xyz = [{
            "path": "photos",
            "name": "photos",
            "children": [
              {
                "path": "photos/summer",
                "name": "summer",
                "children": [
                  {
                    "path": "photos/summer/june",
                    "name": "june",
                    "children": [
                      {
                        "path": "photos/summer/june/windsurf",
                        "name": "windsurf",
                      }
                    ]
                  }
                ]
              },
              {
                "path": "photos/winter",
                "name": "winter",
                "children": [
                  {
                    "path": "photos/winter/january",
                    "name": "january",
                    "children": [
                      {
                        "path": "photos/winter/january/ski",
                        "name": "ski",
                      },
                      {
                        "path": "photos/winter/january/snowboard",
                        "name": "snowboard",
                      }
                    ]
                  }
                ]
              }
            ]
    }];

I attempted to use the following function, but it's not yielding the desired results:

var parsePathArray = function(paths) {
var parsed = [];
for (var i = 0; i < paths.length; i++) {
    var position = parsed;
    var split = paths[i].split('/');
    for (var j = 0; j < split.length; j++) {
        if (split[j] !== "") {
            if (typeof position[split[j]] === 'undefined')
                position[split[j]] = {};
            position.children = [position[split[j]]];
            position.name = split[j];
            position = position[split[j]];

        }
    }
}
return parsed;
}

Answer №1

Just to clarify, I created this response as a way to engage in an interesting exercise. However, it's disheartening that you didn't make an effort to understand and failed to elaborate on the specific areas of confusion...


I took a different approach in my explanation, so rather than copying and pasting the code directly, you'll need to grasp the concept behind it.

Let me briefly outline each step without delving into details that may already be familiar to you.

Step 1:

Transform a list of strings into a list of arrays:

["a/1", "a/2", "b/1"] -> [["a", "1"], ["a", "2"], ["b", "1"]]

We utilize methods like String.prototype.slice to eliminate the leading "/", and String.prototype.split with your chosen delimiter to convert it into an array: path.split("/")

Step 2

Iterate through each folder and include them in an object.

[["a", "1"], ["a", "2"], ["b", "1"]] -> { a: { 1: {}, 2: {} }, b: { 1: {} } }

We leverage a reducer that accesses objects using bracket notation obj[key], creating new folder objects and returning the deepest location as needed.

Step 3

Recursively traverse the keys of your object and transform them into a specific layout:

{ a: { 1: { } } -> { name: "a", path: [], children: [ /* ... */ ] }

We extract a list of keys (folder names) using Object.keys and recursively call for each nested object.


Please update your response by specifying the exact step where you're facing difficulties. This will not only assist others in providing assistance but also allow me to offer a more detailed explanation of that particular step.

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

Displaying identical images repeatedly, alter just one using JQuery with each change

In the design, I have both gray and blue stars displayed multiple times on the page. What I'm trying to achieve is that when a user clicks on a gray star, it should switch to blue, and vice versa. However, the current issue I'm facing is that cli ...

What methods are available to fill a canvas with shapes other than circles?

My goal is to fill the canvas with a black color. The code I have used for this purpose is as follows: var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.fillStyle='rgba(0,0,0,0.1)'; ctx.fillRect(0,0,c.width,c.height) ...

Measuring Internet speed using Node.js

Is there a way to measure internet speed in server-side node.js? I am currently sending the current timestamp from the client side while making an http request. Client side code: var image = document.createElement("img"); image.width = 1; i ...

After the array is printed, the foreach loop is failing to function as expected

I attempted to loop through the given array. Array ( [mech_info] => Array ( [make] => Amaka [0] => Array ( [year] => 2001 [model] => Array ...

"Ensure that all necessary fonts and assets are included in the development of your Vue component

At the moment, I am utilizing vue-cli-service build --target lib --name myLib [entry] to compile Vue into a component library for integration into other projects. Nevertheless, it only produces four files which are: dist/myLib.umd.min.js dist/myLib.umd. ...

Connecting a dynamically assessed function on the $scope to a service

Within my code, there is a function called make_value_summary that has the capability to generate a generic summary of various fields within the $scope. By applying this function, I am able to create location_summary, which is then linked to the view using ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

Trying to set headers in Node/Express after they have already been sent is causing an error

I am attempting to send form data from the client side using jQuery to a POST route that will then pass the data to an API in Node/Express. I am encountering an issue where I receive the error message "Can't set headers after they are sent" and I am ...

Choose a select few checkboxes and then disable the remaining checkboxes using Vue and Laravel

I'm currently working on a project using Laravel 10 and Vue3. In the form, users are allowed to select only 3 checkboxes. Once they have selected 3 checkboxes, all remaining checkboxes should be disabled. I attempted to implement this functionality a ...

Rotating an animated object in ThreeJs: A simple guide

I have modeled a spaceship in Blender, added some random wobbling and rotation animations to it, and then exported the 3D model to ThreeJs. When the user presses the LEFT ARROW key, I want the spaceship to rotate to the left on the X-Y plane, and similarl ...

Is it considered acceptable to utilize a v-model's value as the basis for an if-statement?

How can I incorporate the v-model="item.checked" as a condition within the validations() function below? <table> <tr v-for="(item, i) of $v.timesheet.items.$each.$iter" > <div> <td> ...

Learn the process of adding asynchronous middleware modules to your express.js application

I'm currently developing an express application that utilizes the node_acl module along with a MongoDB database. I have created a custom module that sets up and configures node_acl asynchronously. This middleware needs to be called as the second piece ...

Utilize React-router to display child components on the webpage

Recently, I've encountered some challenges with this code. I have a component that takes in a child as a prop, which is meant to serve as the foundation for all the pages I am hosting. Base.jsx : import React from 'react'; import PropTypes ...

Access your own data, shared data, or designated data with Firebase rules

Seeking guidance on implementing firebase rules and queries for Firestore in a Vue.js application. Requirement: User must be authenticated User can read/write their own data entries User can read data with "visibility" field set to "public" User can rea ...

Create a basic search functionality in an Express Node.js application

Recently, I decided to work on a project to enhance my coding skills. I wanted to create a simple search functionality where the URL would be "/search/(parameter here)" and display products whose names match the parameter. After writing a middleware for t ...

variety of provider setups available in Angular

Trying to learn Angular from various online sources can be quite confusing, as different people use different patterns when writing functions. Can someone please explain the .provider concept in Angular? I have experimented with the .provider method using ...

I am consistently running into an Uncaught Syntax error within my Express server.js while using Angular 1.5.6

I've been struggling for hours to integrate Angular with routes that I've created. Eventually, I decided to give Express a try and set up a basic server.js file to run as a standalone server. However, nothing seems to be working and I keep encou ...

Is there a way to get Axios to display CSS on the page?

While working on a Web Viewer project with axios for web scraping practice, I encountered an issue where the CSS wasn't loading properly. Here is the code snippet I used: console.log("Tribble-Webviewer is starting!") const express = requir ...

I am unsure about implementing the life cycle in Svelte.js

Unknown Territory I am not well-versed in front-end development. Desire to Achieve I aim to utilize the lifecycle method with SvelteJS. Error Alert An error has occurred and the lifecycle method is inaccessible: ERROR in ./node_modules/svelte/index.m ...

Activate SVG graphics upon entering the window (scroll)

Can anyone assist me with a challenging issue? I have numerous SVG graphics on certain pages of my website that start playing when the page loads. However, since many of them are located below the fold, I would like them to only begin playing (and play onc ...