Transforming a List of Items into a Hierarchical Tree Structure

Seeking assistance with constructing a hierarchical tree structure from a flat list that contains categories and names. Various approaches have been attempted, including the function presented below.

The original flat list looks as follows:

var input = [
  {
    "Parent Category": "Agricultural Feed + Seed",
    Category: "Agricultural Feed + Seed",
    Name: "Agfinity"
  },
  ...
];

The desired tree structure based on the flat list is outlined below:

[
  {
    "label": "Agricultural Feed + Seed",
    "children": [
      {
        "label": "Agfinfity"
      },
      ...
    ]
  },
  ...
];

An existing function resembling the one provided attempts to achieve this conversion but may not be optimized.


function formatBrandNames(rawBrands) {
  // Function code here
}

Any advice or suggestions on improving the efficiency of this process would be greatly valued.

Answer №1

The concept can be distilled down to

If the node lacks a parent category, it belongs to the root categories

Determine the Parent through its category, then include the node in the parent's children

In case the parent doesn't exist, create one.

 function convertToTree(nodes) {
   const roots = [];
   const categorizedByCategory = new Map();

   for(const { Name: label, ["Parent Category"]: parent, Category: category } of nodes) {
     const node = { label, children: [] };

     if(categorizedByCategory.has(category)) {
        categorizedByCategory.get(category).children.push(node);     
     } else {
         const categoryObject = {
           label: category,
           children: [node]
         };

         categorizedByCategory.set(category, categoryObject);

         if(parent === category) {
           roots.push(categoryObject);
        } else if(categorizedByCategory.has(parent)) {
           categorizedByCategory.get(parent).children.push(categoryObject);
        } else {
           categorizedByCategory.set(parent, { label: parent, children: [categoryObject] });
        }
     } 


   }

   return roots;
 }

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

Get the results of a MongoDB projection query in Javascript/Node.js by converting the output to

When using a query with projection to retrieve specific fields from a MongoDB collection, do I need to output the results of the query to an array? I haven't come across any examples that don't involve converting the results to an array. db.coll ...

Add a fresh widget to the DOJO attachment point without overwriting

Here is some code I have: postCreate: function() { this.items.forEach(lang.hitch(this, function(item) { new SideNavigationItem({ name: item.name }, this.container); })); } This code snippet ...

How can you center popup windows launched from the main window using jquery?

Within my web application, I frequently utilize popup windows that open at different locations on the screen. These popups are standard windows created with window.open() rather than using Jquery. Now, I am seeking a solution to automatically center all p ...

Could anyone clarify the concept of how a function is able to be equivalent to zero?

function checkForSpecialCharacters(text) { var specialChars = [";", "!", ".", "?", ",", "-"]; for(var i = 0; i < specialChars.length; i++) { if(text.indexOf(specialChars[i]) !== -1) { return true; } } ...

What is the best way to add stripes to a button for a colorful touch

Can the button be styled with colors similar to those shown in the image? https://i.sstatic.net/3o1Jb.png ...

Combine adjacent items in an array to streamline the list

Is there a method to condense consecutive duplicate items in an array into one item? Consider the following array: int[] array = new int[]{ 1, 2, 2, 3, 3, 4, 5, 3, 2 }; If we remove duplicate items that are next to each other, the modified array would l ...

What is the most efficient way to transfer substantial data from a route to a view in Node.js when using the render method

Currently, I have a routing system set up in my application. Whenever a user navigates to site.com/page, the route triggers a call to an SQL database to retrieve data which is then parsed and returned as JSON. The retrieved data is then passed to the view ...

Steps for raising a unique error in an asynchronous callout

As I work on making async API callouts, there might be a need to throw custom errors based on the outcome. Also, part of this process involves deleting objects from S3. try { await s3.deleteObject(bucketParams); //Since S3 API does not provide ...

Error: JSON response is returning as undefined

Whenever I attempt to display the height and weight data from an API (), I encounter an issue: Error: TypeError: Cannot read properties of undefined (reading 'metric') If I remove the "items.height.metric", everything runs smoothly, however, I ...

Creating a carousel with three thumbnails arranged in two rows

Currently, I am using a slider for my thumbnails. If you want to check out the code for this thumbnail slider, click on this link: thumbnails slider code My goal is to display 6 thumbnails in total, with 3 thumbnails shown in each row (2 rows total). Add ...

Is there potentially a memory leak in this code? If there is, what steps can be taken to eliminate it?

Recently I inherited a project from my senior colleagues that focused on seamless page reloading using AJAX. The code is filled with numerous functions like this one: function iCreateProblems() { //some random code document.getElement ...

Issues with displaying calendar items on the React timeline are only resolved after pressing F12 or resizing the

I am encountering a problem while trying to plot the items array in the timeline calendar. Interestingly, the groups array is working fine. The items array also functions properly when values are provided manually. However, the items only render after pre ...

"Encountered a roadblock while attempting to utilize the applyMatrix

I am currently working on running an animation using a JSON file and a custom JSON loader, not the one provided with three.js. Within the JSON file, there is an object called frames that contains multiple frames, each with shape information and a simulatio ...

Encountering an unfamiliar group operator error '$group' in MongoDB

Attempting to calculate the number of distinct (not unique) Emp No in the same department, but encountering an error. Error: Unknown group operator '$group' Code snippet can be found here: https://mongoplayground.net/p/UvYF9NB7vZx db.collectio ...

Retrieve webpage using HTML stored in web storage

I am exploring a new idea for an application that utilizes local storage, and I am seeking guidance on the most effective way to load content after it has been stored. The basic concept of the app involves pre-fetching content, storing it locally, and the ...

While experimenting with p5.js, I encountered an issue where I received the error message stating that "loadAnimation is not defined and createSprite not defined." This problem persists even when using VSCode

let background, sleeping, brushing, gyming, eating, drinking, moving, astronaut; function preload() { background = loadImage("images/iss.png"); sleeping = loadAnimation("images/sleep.png"); brushing = loadAnimation("images/ ...

Using Bootstrap4 tagsinput, removing a tag: detecting for AJAX fulfillment and then reversing the action

Utilizing tagsinput in conjunction with bootstrap4, my goal is for the user to be able to delete a tag by clicking on the 'x' button. Upon deletion, an ajax request is sent to the server to verify if the user has permission. The server will respo ...

In JavaScript or jQuery, what is the most optimal method to swap out all instances of a specific string within the body content without altering the rest of the body text?

Is there a way to replace specific occurrences of a string within a web page's body without disrupting other elements such as event listeners? If so, what is the best method to achieve this? For example: Consider the following code snippet: <body ...

Retrieving a specific section of key values in a PHP array

There seems to be an array structured like this, and I am looking to extract the first 2 parts of each key. Some keys have 5 strings separated by ',' while others have 2 strings separated by a ',' Ex: array ( 'kksgzgg , kdhdhk ...

There is nothing like Python Bottle when it comes to parsing JSON data from

In my React code, I have the following: const payload = { x : x, y : y } fetch("http://localhost:8080/update_game", { method: "POST", body: JSON.stringify(payload)}) And in Python, I have this implementation: @post(&ap ...