Creating a hierarchical menu structure by splitting strings in an array using an algorithm

I have an array of strings in Javascript that look like this:

var array = [{
  string: 'path1/path2/path3'
}, {
  string: 'path1/path4/path5'
}, {
  string: 'path1/path2/path6'
}, {
  string: 'path10/path7'
}, {
  string: 'path10/path8/path9'
}];

My goal is to create a data model with the following structure:

-- path1
  -- path2
    -- path3
    -- path6
  -- path4
    -- path5
-- path10
  -- path7
  -- path8
    -- path9

Any suggestions on how I can achieve this? Thank you!

Edit:

I was considering something like:

var paths = {
  children: [
    { 
     name: "path1",
     children: [
      { 
       name: "path2", 
       children: [
        { 
         name: "path3", 
         children: []
        }]
      },
      {
       name: "path4", 
       children: [
        { 
         name: "path5", 
         children: []
        }]
      }
    }
   ],
   .......
};

Answer №1

Here is a simple script to help you get started:

const paths = [{
  name: 'path1/path2/path3'
}, {
  name: 'path1/path4/path5'
}, {
  name: 'path1/path2/path6'
}, {
  name: 'path10/path7'
}, {
  name: 'path10/path8/path9'
}];

let directoryTree = {};

for (let {name} of paths) {
    let temp = directoryTree;
    for (let segment of name.split('/'))
        temp = temp[segment] || (temp[segment] = {});
}

console.log(directoryTree);

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

Choosing read-only text fields using JQuery

I am working on an ASP.NET MVC project and I am looking to select all text boxes with the "readOnly" attribute on the current page. Once identified, I want to trigger a modal jQuery dialog on keypress for each of these disabled text boxes. Any suggestion ...

Ways to retrieve the value of "name" in the JSON file provided below

[ { "_class": "hudson.model.FreeStyleProject", "name": "actual_build", "url": "http://tepl.tallycloudinfra.com:8080/job/actual_build/", "color": "blue", & ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

Instant access to an interactive online platform

Is it feasible to create a shortcut from a webpage to my desktop for quick access? For instance, if a dynamic web page has 15 documents and I want to easily create shortcuts to them on my desktop by clicking on each one. I understand this is a brief quest ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

The issue arises when a continuous use of angularjs directives linked with an external template fails to display correctly upon the addition of new

In the code snippet below, you'll find a fiddle that displays 3 columns of numbers that increase in value. These columns represent directives with different templates: one inline, one preloaded, and one from an external template. When you click on the ...

How can I revert a date format using date-fns?

Greetings from Thailand! I have a question regarding the reverse formatting using date-fns. Is there a way to create a function that will change "saturday-9-september-2564" back to "2022-09-24" using date-fns? Any insights or methods on achieving this wo ...

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

Strangely unusual issues with text input boxes

So I've set up two textareas with the intention of having whatever is typed in one appear simultaneously in the other. But despite my best efforts, it's not working as expected. Here's the code snippet: <script> function copyText () { ...

What is the process for deselecting text from a text field?

After performing a search and displaying the results on my search form, I've noticed that the text query in the textfield is being marked as selected text even though I don't want it to be. How can I prevent this? Fiddle 1) What is the best app ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

Oops: Looks like there is already a request for 'PUBLIC_requestAccounts' pending from http://localhost:3000. Just hold tight for now

There comes a moment when an unexpected error arises and fails to establish a connection with your wallet. if (window.ethereum) { console.log("11") const connect = async () => { const account = await window.ethereum.request({ ...

The index.ngfactory.ts file threw an unexpected token error, indicating that an appropriate loader may be necessary to handle this specific file

I've spent several hours trying to troubleshoot this persistent error, exhausting all online resources for solutions. The issue arises consistently with every module of Angular Material only during the build process using --env.prod. The webpack confi ...

Issue with cross-origin in Salesforce reply (Access-Control-Allow-Origin)

While attempting to retrieve records from Salesforce using external local files via JS, I encountered an issue. Although I can see a response in the network tab, the console displayed the following error message: "XMLHttpRequest cannot load . No 'A ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Time whizzes by too swiftly

After attempting to create an automated slideshow with clickable buttons, I encountered a problem. The slideshow functions properly, but as soon as I click one of the buttons, the slideshow speeds up significantly. This is what I implemented in my attempt ...

Is it possible to delete an element from both local storage and HTML by referencing its ID?

Experience a simple flashcard game where you enter a question and answer to create a new flash card stored as an object within the cards array. The newly created flash card is also displayed by appending a new element to the flash cards section on the webp ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...