Transforming and categorizing a string array into a tree structure

Array showing different included elements:

var exampeInclude= [
  "Product",
  "Group",
  "Product.Tax",
  "Product.ProductUnit",
  "Product.Variant.Original",
  "Product.Variant.Original.Tax",
  "Product.Variant.Original.ProductUnit"
];

Desired hierarchical structure from the array:

 [
    {
        "Product": {
            "includes": [
                {
                    "Tax": {
                        "includes": []
                    }
                },
                {
                    "ProductUnit": {
                        "includes": []
                    }
                },
                {
                    "Variant": {
                        "includes": [
                            {
                                "Original": {
                                    "includes": [] //...
                                }
                            }
                        ]
                    }
                }
            ]
        }
    },
    {
        "Group": {
            "includes": []
        }
    }
]

Attempting to achieve a tree-like structure but facing challenges with debugging and iteration. Progress made using a simple reduce function, however struggling with implementing the split('.') method. Is recursion necessary for this task?

Current approach using reduce function:

var hist = exampeInclude.reduce(function (prev, item) { 
  if( item in prev ) prev[item] ++; 
  else prev[item] = 1; 
  return prev;  
}, {});

(Basic counting functionality implemented using reduce function as starting point)

Answer №1

I propose constructing a tree structure based on the given path, and then incorporating an 'includes' array for intermediates

function buildTreeFromPath(tree, path){
  var pathArray = path.split('.'),
     parentNode = tree;
  for(var index = 0; index < pathArray.length; index++){
     var node = pathArray[index];
     if(!(node in parentNode))   parentNode[node] = {};
     parentNode = parentNode[node];
  }
}
var exampleIncludes= [
  "Product",
  "Group",
  "Product.Tax",
  "Product.ProductUnit",
  "Product.Variant.Original",
  "Product.Variant.Original.Tax",
  "Product.Variant.Original.ProductUnit"
],
treeStructure = {};
for(var i = 0; i < exampleIncludes.length; i++){
   buildTreeFromPath(treeStructure, exampleIncludes[i]);
}
// At this point, the tree structure should have been created
// resembling {Product:{Tax:{},ProductUnit:{},Variant:{Original:{Tax:{},ProductUnit:{}}}},Group:{}}
// Next step is to format the object with intermediate includes
function addIntermediates(obj){
   var result = [];
   for(var name in obj){
     var childObj = obj[name];
     result.push(childObj);
     childObj.includes = addIntermediates(childObj);
   }
   return result;
}
var finalResult = addIntermediates(treeStructure);

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

Tips on distinguishing the original Ctrl+C and Ctrl+V commands from the Javascript-added document level listeners

My Clipboard service includes a copy() and paste() method that is triggered by Ctrl+C and Ctrl+V commands. These methods are document-level keyboard listeners added to a component using HostListeners. However, I am facing an issue where the paste() method ...

I am unsuccessful in transferring the "side-panel content" to the side panel located on the main menu page

I am facing an issue where I want to pass My left and right Panel to the main menu page (dashboard), but it is not working as expected. The problem arises because the first page that needs to be declared is the login page (/ root) in my case. If I pass it ...

Guidelines for retrieving a class name using jQuery when hovering over a div

I need assistance in fetching the class name by hovering over a div. Both divs have the same id but slightly different class names. Here is an example: <div id="1-someid" class="1-example-class border cz"> ...more elements go here.... </div> ...

Reloading a page will display [object CSSStyleDeclaration]

Upon editing content and saving changes, instead of displaying my updated content when refreshing the page, it shows [object CSSStyleDeclaration]. function newElement() { let li = document.createElement("li"); let inputvalue = document.querySelector ...

Transferring Information between a Pair of Controllers

Currently, I am utilizing angular version 1.x and faced with the challenge of sharing data between two controllers. In my mainctrl, I am working with the above model. The radiotmplt.radiohead=='IRU600v3' is utilized in firstctrl. Unfortunately, ...

Encountering a "400 Bad Request" error when using Ajax within WordPress

I've been trying to submit a form using Ajax within a plugin. I had two plugins, the first one was initially working but has stopped now and I can't seem to find any errors. I don't think the issue lies in the code itself, but I'm feeli ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

Pass multiple parameters in a single line using FormData() function

I have a question about my React project. Currently, I am using the following syntax: const data = new FormData(); data.append("token", this.props.token); data.append("origin", this.props.origin); .... My question is: Is there a way to condense these ap ...

Show a success message, clear the post data, and redirect back to the current page

I have a single web page with a contact form. When the form is submitted, I want it to redirect to the same page and display a success message that fades out after a few seconds. Additionally, I want the post data of the form to be cleared. The form also i ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Exploring the contrasting outcomes between a request post and an axios post

After using request and wrapping it with a promise, I realized that I could write cleaner code by switching to axios. However, I encountered an internal server error (Request failed with status code 401) and since I don't have access to the backend co ...

Unable to simultaneously execute TypeScript and nodemon

Currently, I am in the process of developing a RESTful API using Node.js, Express, and TypeScript. To facilitate this, I have already installed all the necessary dependencies, including nodemon. In my TypeScript configuration file, I made a modification to ...

Navigating an HTML table with the precision of a battleship commander: A guide

I have a simple HTML table that I want to parse line by line using JavaScript without any specific identifiers like class names. My goal is to create a mapping system similar to the following: AC000(red)(green) => cell match. As illustrated in the scr ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

The angular view is lacking a CSS class

index.html: <div ng-view="myview.html"></div> myview.html: <table class="table table-striped table-hover"> <tr> <td>Name</td> <td>Product</td> </tr> <tr ng-repeat="deal in deals" class="clickableR ...

"Troubleshooting the issue with the @click event failing to update the data

Working in Vue.js, my v-for loop is set up to go through a list and generate buttons. Each button has a click event that should change the value of upUrl to its index: <div class="mt-3" v-for="(buttonPic, index) in buttonPics" ...

Employing the `signInWithRedirect` method with an `authDomain` that does not match the app's domain will result in an incomplete sign-in process, without any error notifications being displayed

I'm currently transitioning from using Firebase's signInWithPopup method to the signInWithRedirect method. After reading through the best practices outlined in this documentation, I realized that not following these practices can result in succe ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

Ways to prevent modal from flickering during event changes

I'm struggling with a current issue and need help identifying the cause and finding a solution. The problem arises from having a nested array of Questions, where I display a Modal onClick to show Sub questions. However, when clicking on the Sub Quest ...

In this JavaScript code, learn how to organize an array based on its numerical property

What is the best way to organize an array based on the 'num' property in this JavaScript array? var data = [{ 005: { `num`: 1360487}, 047: { `num`: 2519472}, 061: { `num`: 1559115}, 081: { `num`: 2232710}, 085: { `num`: 54956 ...