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

Mongooses do not clutter the array with unnecessary lines

I need help generating a sorted list from the database. Here is my current code: const subs = await Sub.find({}, {userName: 1, score: 1, _id: 0}).sort({ score: 'desc' }); The output I am getting looks like this: { userName: 'test1', ...

What is the best way to transfer variables from an ng-template defined in the parent component to a child component or directive?

Is there a way to pass an ng-template and generate all its content to include variables used in interpolation? As I am still new to Angular, besides removing the HTML element, do I need to worry about removing anything else? At the end of this ...

What is the reason for the unique behavior of v-bind with boolean attributes? More specifically, why is the number 0 considered truthy in

According to the official documentation, <button v-bind:disabled="isButtonDisabled">Button</button> In this example, the disabled attribute will be added if isButtonDisabled is equal to 0, despite the fact that in JavaScript, 0 is co ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Avoiding repetitive rendering of child components in ReactJS

In my React project, I have a parent component that contains 3 children components, structured like this: var Parent = React.createClass({ render: function() { return (<div> <C1/> <C2/> <C3/> ...

Manipulating Strings in JavaScript

Hi there, I'm a beginner in JavaScript and I could really use some help with the following question. So, let's say I have this string: "AB_CD.1.23.3-609.7.8.EF_HI.XBXB" The numbers 1.23.3 and 609.7.8 are completely random with two dots separat ...

Two entities positioned on opposite extremes

Is there a way to design a div with two elements (text and image) positioned on opposite sides? The length of the text varies as it's a list of months for selection. Ideally, the text should appear on the left side of the div as a "p" element, while t ...

New to NodeJS: Utilizing Requestify to Retrieve Data from Another URL

As a newcomer in the world of NodeJs, I am faced with the task of transitioning my CodeIgniter server APIs to Node.js. Currently, I am utilizing requestify to retrieve data from a web service, and once this is accomplished, I intend to invoke an insert met ...

Using ajax to submit a form in CodeIgniter and displaying the returned data in a table view

When I submit a form on the view page, I want the form data to be saved in a database table and displayed without refreshing the page. Below is my view code: <div class="col-md-12"> <div class="row"> <div> <table class="table table-s ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Writing in Node.js involves setting up a local DynamoDB for local development rather than running it in an actual Lambda

This straightforward aws.js script is used to execute dynamoDB operations locally. "use strict"; const AWS = require("aws-sdk"); AWS.config.dynamodb = { region: "eu-west-2", endpoint: "http://localhost:8000& ...

Trouble displaying loaded JSON data with $http GET in ng-table

I have recently delved into learning angularjs and am currently experimenting with using ng-table to display the results of blast searches. Everything runs smoothly when I directly add the JSON data in the JavaScript script. However, I have been unsuccess ...

Having trouble positioning a div in AngularJS so that it stays pixel-perfect regardless of browser resize or device orientation? Unfortunately, it's

I am a newcomer to AngularJS and have been struggling with a particular issue for several days now, leading me to suspect that I may be using it incorrectly. The problem at hand involves positioning 30 divs in a specific manner: 1) Each div should displa ...

Failed Axios POST request on iOS devices

Attempting a straightforward ajax POST from domain1 to domain2 using Axios. This involves a cross-domain simple POST without requiring a PREFLIGHT (OPTIONS) call. The response returned by the application is a basic JSON string. This process functions smoo ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

Executing npm run build index.html results in a blank page being generated without any error messages or warnings

After building my react app with npm run build, I encountered a problem where clicking on index.html resulted in a blank page opening in the web browser. I explored several solutions to address this issue but none seemed to work. Some of the strategies I ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

Exploring AngularJS with Filtering for Advanced Search Results

Currently, I have a search box that successfully searches values in a table using my code. <tr ng-repeat="b in bugs | filter:searchText"> Now, I want to take it one step further by allowing users to search specific columns if they include a colon i ...

Nodejs registration and user verification process for accessing account features

I am facing a decision on how to handle two types of users - vendors and buyers. Should I develop separate APIs for registering and authenticating each user type, or should I create a single API to manage both? When designing my database model, should I h ...

What steps can be taken to address the error message "FATAL: Unable to load template" encountered while using

I'm encountering the issues documented here and here on GitHub. I'm working on incorporating documentation for my Next.js code, and below is my jsdoc configuration file. { "tags": { "allowUnknownTags": true, "di ...