Generating a tree structure in Javascript using an array of Objects that hold path information

I have successfully created a folder tree using a list of string paths. Now, I want to take it a step further and make it work with objects instead.

    var paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"],
            result = paths.reduce((r, p) => {
              var names = p.split("/");
              names.reduce((q, name) => {
                var temp = q.find(o => o.name === name);
                if (!temp) {
                  q.push((temp = { name, children: [] }));
                }
                return temp.children;
              }, r);
              return r;
            }, []);

            console.log(result)

Instead of an array of paths, I now have an array of objects with paths:

var paths = [{
  path: "/media",
  id: 9,
  name:"media"
},{
  path: "/media/folder1",
  id: 1,
  name:"folder1"
},{
  path: "/media/folder1/child",
  id: 3,
  name: "child"
},
{
  path: "/media/folder2",
  id: 2,
  name: "folder2"
}];

The desired output should look like this:

 [
  {
    "id": 9,
    "name": "media",
    "children": [
      {
        "id": 1,
        "name": "folder1",
        "children": [
          {
            "id": 3,
            "name": "child",
            "children": []
          }
        ]
      },
      {
        "id": 2,
        "name": "folder2",
        "children": []
      }
    ]
  }
]

Answer №1

To implement the code snippet you provided, all you need to do is modify a single line:

const [root, ...names] = p.path.split("/");

Add an additional line:

const id = p.name == name ? p.id : undefined;

Also, update one last line:

q.push((temp = { id, name, children: [] }));

const paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"];

const paths2 = [
  {
  path: "/media",
  id: 9,
  name:"media"
},...
];

const out1 = createTree(paths);
const out2 = createTree(paths2);

function createTree(input){
  const result = input.reduce((r, p, i) => {...});
  console.log(result)
  return result;
}

Here is the resulting output:

[
  {
    "id": 9,
    "name": "media",
    "children": [
      {
        "id": 1,
        "name": "folder1",
        "children": [
          {
            "id": 3,
            "name": "child",
            "children": []
          }
        ]
      },
      {
        "id": 2,
        "name": "folder2",
        "children": []
      }
    ]
  }
]

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

Trigger a function with AngularJS when the page loads

I'm currently studying AngularJS. I have a set of article tags and want to display each article page without refreshing the page when a button is clicked. This website consists of only one page. The issue I am facing is that despite trying to call myF ...

Troubleshooting Mobile App Errors with Rails API

My mobile application is connected to a Rails server. I am encountering an issue when attempting to edit an Item in the Rails database using a JSON request from my application. The first time I make the AJAX request, I receive an error message. {"readySta ...

Green and red values hovering within the keyframe

Currently, I'm facing a dilemma involving keyframes. I have a table populated with values retrieved from a JSON fetch and need to implement a hover effect where values less than 5 show in red, while those equal to or greater than 5 appear in green. Be ...

"Enhance your PHP skills by learning how to convert database results, represented as strings, into arrays using the explode function and effectively adding them to

In need of creating a multidimensional array with specific elements: $arrayTwo = [ [ 'This','array','needs','to','be','filled'], ['This','cat','needs','to', ...

Remove item from jQuery's "raw text" HTML

Suppose I have the following JavaScript string: var string = '<div id="div1"><div id="div2"></div></div>'; Is it possible to utilize jQuery in order to create a new string as shown below? var newString = '<div i ...

Two consecutive instances of the outcome recorded in the ajax table

I am trying to add data to a table, but one of my results is appearing twice. Here is the JSON response I received: groupname […] 0 {…} survey_id 2 group_name DEMO 1 {…} survey_id 1 group_name TEST This is what my AJAX success function ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

Tips for successfully integrating .dae files into three.js for online execution on a web browser

Hey everyone, I'm an HTML developer who has never worked with WEBGL technology before. I've been trying to figure out how to pass a .dae file into 'three.js' by searching through numerous websites, but I haven't been successful. C ...

Using Vuejs to dynamically render raw HTML links as <router-link> elements

Hey there, I'm just getting started with VueJS and I've been doing some interesting experiments. I created a backend service using Python/Flask that provides me with a string of HTML code containing many tags. My goal is to render this HTML insid ...

Converting string components into actual components in Vue: A step-by-step guide

I have a specific need for a plugin store where I want to load a component from the core into plugins and then convert that string into an actual component within the plugin for usage. Please suggest better approaches for implementing the plugin store wit ...

Is it possible that activating the alert() function within a Node.js script could cause the server to freeze completely?

Given that Node.js operates on a single thread, is there a risk of freezing the entire server by calling functions like alert(), which typically wait for user input? Does Node.js have mechanisms in place to prevent such issues? ...

How to locate the position of a specific word on a webpage using jQuery

In my div, I am struggling to search like an editor. Despite multiple attempts, I have not found a solution yet. Can someone please advise me on how to resolve this issue? <div id="content"> <p> Lorem Ipsum is simply dumm ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...

Parallax effect overlay for DIV

Planning to give my website a makeover and I'm thinking of adding some parallax effects to make it more engaging. My idea is to have 3 boxes overlapping each other (with the 2nd and 3rd box appearing blurry). These boxes would be placed at the top of ...

Alignment of pointers and array length storage

In my exploration, I stumbled upon an interesting implementation of an array that cleverly stores its length "inside" it. Take a look at the code snippet below: double* createArray(const size_t size) { double* arr = malloc(sizeof(double) * size + sizeof ...

Error: The Firebase App named `[DEFAULT]` does not exist, despite calling the initializeApp function

I'm currently facing an issue while trying to integrate Firebase (Firestore) into my Nuxt project. When I try to initialize a const using firebase.firestore() in my index.vue file, I encounter the following error: Uncaught FirebaseError: Firebase: N ...

I am unable to locate the type definition file for 'core-js' at the moment

Currently, I am in the process of developing an application using angular2 along with angular-cli. Surprisingly, angular-in-memory-web-api was not included by default. In order to rectify this, I took the initiative to search for it and manually added the ...

Can you explain the process of variable allocation?

I have a query regarding the following JavaScript code snippet. It might be a basic question, but I'm seeking clarification. // 'response' contains JSON data received from the backend: ....then(response => { this.myVar = response.data; ...

Unable to make changes to a file authored by a different user within Firestore using Vue.js / Firestore

I appreciate any assistance in advance, as this issue has been causing me a lot of frustration! Currently, I am adhering to the firestore data model where users are able to create their own documents associated with their userID. This ensures that users c ...

I am struggling with utilizing the data that has been fetched in JavaScript. Despite successfully retrieving the data, I am facing difficulties in effectively using it in

I am facing an issue where I am unable to utilize the data after fetching it from a local JSON file. Below are the screenshots showcasing the problem: Here is the data displayed in the console: Here is the code snippet: fetch('api_link.json') ...