Building a PathString Tree

I encountered a similar issue like the one discussed in this post (Get a tree like structure out of path string). I attempted to implement the suggested solution but I am facing difficulties getting it to work within an Angular context.

The concept involves parsing incoming path strings (as shown below) and organizing them into an object to be displayed as a tree.

 pathStrings: string[] = [
    "PathA/PathA_0",
    "PathA/PathA_1",
    "PathA/PathA_2/a",
    "PathA/PathA_2/b",
    "PathA/PathA_2/c"
  ];
  let tree: Node[] = [];

    for (let i = 0; i < this.pathStrings.length; i++) {
      tree = this.addToTree(tree, this.pathStrings[i].split("/"));
    }

// function addToTree...

const TREE_DATA: Node[] = [
  // Tree data example...
];

</div>
<p>The expected output should resemble the following tree structure:</p>
<div>
<pre class="lang-js"><code>const TREE_DATA: Node[] = [
  // Tree data sample...
];

Here is the link to the Stackblitz demo showcasing my attempts: https://stackblitz.com/edit/angular-h3btn5?file=src/app/tree-flat-overview-example.ts. I have been trying for days with no success. Any help would be greatly appreciated. Thank you!

Answer №1

If you're looking to reduce an array in plain Javascript, one approach could be to utilize a recursive function for the searching process and then assign the new child to a specified node.

const
    buildTree = (node, keys) => {
        const key = keys.shift();
        let child = (node.children ??= []).find(item => item.key === key);
        if (!child) node.children.push(child = { key });
        if (keys.length) buildTree(child, keys);
        return node;
    },
    pathItems = ["ItemA/ItemA_0", "ItemA/ItemA_1", "ItemA/ItemA_2/a", "ItemA/ItemA_2/b", "ItemA/ItemA_2/c"],
    treeStructure = pathItems
        .reduce((target, path) => buildTree(target, path.split('/')), { children: [] })
        .children;

console.log(treeStructure);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

You are unable to assign to 'total' as it is a constant or a property that cannot be modified

Upon running ng build --prod in my project, I encountered the following error: src\app\components\xxxx\xxxx.component.html(116,100): : Cannot assign to 'total' because it is a constant or a read-only property. The proble ...

Constantly positioning the text cursor over the Textbox

I am currently in the process of developing a webpage that will feature only one text box for displaying information based on the input data provided. Our strategy involves utilizing either a Barcode Scanner or Magnetic Swipe as well as a Touch Screen Moni ...

How to save data to a JSON file using the filesystem module in Node.js

After coming across this helpful guide at , I was intrigued by the creation of a point system in discord.js. The use of let points = JSON.parse(fs.readFileSync("./points.json", "utf8")); to read the file piqued my interest, leading me to explore how to bui ...

Utilizing ExpressJS to refresh database query after new record insertion

I'm a beginner in using expressJS and I have a question about querying the database (mongo in this case) to retrieve all records after adding one. exports.get = function (db) { return function (req, res) { var collection = db.get('n ...

The AudioPlayerStatus module in Discord JS is a powerful tool for managing

Could you explain why this code snippet: client.player.once(AudioPlayerStatus.Idle, () => { console.log(client.playlist); next.run(message, args, client); client.playlist.shift(); return; }); is b ...

The "ngx-phone-select" directive is not defined with the "exportAs" attribute

Having an issue with ngx-phone-select in the phone number field, receiving the error message "There is no directive with "exportAs" set to "ngx-phone-select" http://prntscr.com/hzbhfo This problem occurs in Angular 4.3 using ngx-phone-select version 1.0. ...

What steps can I take to avoid keypress events causing issues with the browser's input functionality?

Utilizing Bootstrap's modal component, I have implemented an "Add User" dialog within my web application. In order to streamline the user experience and enable quick data entry, I am aiming for the escape and enter keys to close and submit the form re ...

Is it possible for node-java to accept anonymous functions as parameters in Java?

I am looking to pass an anonymous function from JavaScript to Java using node-java (https://github.com/joeferner/node-java). Below is a snippet of the Java code for reference: public class Example { public Example() { } public interface Callb ...

Error message: "ExpressionChangedAfterItHasBeenCheckedError in dynamic reactive forms"

This issue arises when utilizing nested reactive forms and the child component employs ng-if*. It's the template interpolation that leads to complications. You can refer to the reproduction here: https://plnkr.co/edit/GrvjN3sJ05RSNXiSY8lo //our root ...

Is the Positioning of JS Scripts in Pug and Jade Documents Important?

Have you ever wondered why a page loads faster when certain lines are placed at the end of the tag instead of inside it? script(src="/Scripts/jquery.timeago.js") This phenomenon is often seen in code like this: //Jade file with JQuery !!! 5 html(lang=" ...

Why is it necessary to define a property outside the constructor in Typescript, when in Javascript I wouldn't have to do that?

When working with Javascript, creating a class like the one below allows us to avoid declaring and initializing a property named logs outside of the constructor: class Logger { constructor() { this.logs = []; } } However, transitioning to TypeScri ...

What is the process for verifying the size of file uploads using Multer in Express?

Currently, I am utilizing Multer as the `multipart/form-data` middleware in Express. My main query revolves around how to verify the size of uploaded files, especially during the uploading process. I understand that you can define limits in the options ob ...

Trigger a PrimeNG p-datatable event when a new row is inserted

My p-datatable is linked to a list of entries. I am trying to focus on newly created rows dynamically, specifically on an input within the new row. How can this be achieved? Every time a new entry is added to the list, a new row is appended in the datatab ...

What is the best way to update text in an element when hovering or activating it?

I am currently designing a website with a prominently placed "Hire me" button in the center of the page. The button was implemented using the following code: <div id="hire_me_button"> <a href="contact.html"><h4 id="hire_me" class="butto ...

A guide to creating test cases for conditional statements in Angular using Jasmine

I am currently working on creating test cases for a custom directive in Angular. I have shared my code on StackBlitz. I would appreciate any guidance on how to address the highlighted if else statements below: if (trimmedValue.length > 14) { // Loo ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

The API response was blocked due to the CORS header "Access-control-allow-origin."

I have an index.html file that is used for making HTML and Ajax calls. When I run the file through localhost, the API works perfectly. However, if I directly open the index.html file in Google Chrome or Mozilla Firefox, I encounter a CORS (Cross-Origin Re ...

Sluggish Bootstrap Carousel Requires Mouseover or Click to Start Sliding

Having Trouble with Bootstrap Carousel Sliding: I've been trying to solve this issue for a while now, but nothing seems to be working. I know this might be a common question, but I really need to fix this problem quickly and none of the suggested solu ...

The Checkbox component from Material-UI does not seem to be compatible with the Redux

The data source can be found in this repository Although I am using Redux store to update the checkbox's check flag and observing that the state changes correctly, unfortunately, these modifications are not reflecting on the React components. It see ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...