The input I have is an array that has been flattened, and I am looking to transform it into a tree structure

Additionally, the node with a null value for the parent_uid is considered as the highest-level node. Input -:

[
{uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f", parent_uid: null},
{uid: "c64eb64e-1291-4833-b646-947f1a64a1cf", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "93976670-6272-4cca-ac18-73bb3345d95c", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "17c19db6-cde9-4581-a49e-c279faae922c", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "ebb92286-58e5-49dc-a9db-30a5aec378b0", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "df25c86a-b34a-42f4-8c4c-7c419dc97dc8", parent_uid: "df25c86a-b34a-42f4-8c4c-7c419dc97dc8"},
{uid: "f3bbe5bf-d56b-4e00-9991-40f27cf2b8e8", parent_uid: "df25c86a-b34a-42f4-8c4c-7c419dc97dc8"},
{uid: "9de2cd38-ba16-4ec0-bcd7-b2d1a4a75e3f", parent_uid: "df25c86a-b34a-42f4-8c4c-7c419dc97dc8"},
{uid: "f800ed46-a894-418e-bb3a-e0c317a244fa", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "11eb90e1-b527-4e88-be70-cad4a2a60bdd", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "aaa6ff31-13d2-57d0-ef49-d8962884cedb", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "81004b95-37e8-9096-918c-64fbab3b7cd7", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "1cfdacf8-c7bb-481c-503a-ef88665a07c9", parent_uid: "d86161ab-1838-4cd3-afc2-20a32c08e88f"},
{uid: "13e4e12a-2e33-f69f-fe83-5fb9c2d7a869", parent_uid: "9de2cd38-ba16-4ec0-bcd7-b2d1a4a75e3f"},
{uid: "c480d612-0a67-105f-efc1-dd248962f1fd", parent_uid: "9de2cd38-ba16-4ec0-bcd7-b2d1a4a75e3f"},
{uid: "44a7b3c8-5672-fac1-1b98-1f173cab2737", parent_uid: "13e4e12a-2e33-f69f-fe83-5fb9c2d7a869"}
]

Answer №1

One way to tackle this problem is by utilizing a recursive approach with the `reduce` method, passing down the `uid` and then verifying it against the `parent_uid` in subsequent calls.

const data = [{"uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f","parent_uid":null},{"uid":"c64eb64e-1291-4833-b646-947f1a64a1cf","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"93976670-6272-4cca-ac18-73bb3345d95c","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"17c19db6-cde9-4581-a49e-c279faae922c","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"ebb92286-58e5-49dc-a9db-30a5aec378b0","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"df25c86a-b34a-42f4-8c4c-7c419dc97dc8","parent_uid":"df25c86a-b34a-42f4-8c4c-7c419dc97dc8"},{"uid":"f3bbe5bf-d56b-4e00-9991-40f27cf2b8e8","parent_uid":"df25c86a-b34a-42f4-8c4c-7c419dc97dc8"},{"uid":"9de2cd38-ba16-4ec0-bcd7-b2d1a4a75e3f","parent_uid":"df25c86a-b34a-42f4-8c4c-7c419dc97dc8"},{"uid":"f800ed46-a894-418e-bb3a-e0c317a244fa","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"11eb90e1-b527-4e88-be70-cad4a2a60bdd","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"aaa6ff31-13d2-57d0-ef49-d8962884cedb","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"81004b95-37e8-9096-918c-64fbab3b7cd7","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"1cfdacf8-c7bb-481c-503a-ef88665a07c9","parent_uid":"d86161ab-1838-4cd3-afc2-20a32c08e88f"},{"uid":"13e4e12a-2e33-f69f-fe83-5fb9c2d7a869","parent_uid":"9de2cd38-ba16-4ec0-bcd7-b2d1a4a75e3f"},{"uid":"c480d612-0a67-105f-efc1-dd248962f1fd","parent_uid":"9de2cd38-ba16-4ec0-bcd7-b2d1a4a75e3f"},{"uid":"44a7b3c8-5672-fac1-1b98-1f173cab2737","parent_uid":"13e4e12a-2e33-f69f-fe83-5fb9c2d7a869"}]

function toTree(data, pid = null) {
  return data.reduce((r, e) => {
    if (pid === e.parent_uid) {
      const obj = { ...e }
      const children = toTree(data, e.uid);
      if (children.length) obj.children = children;
      r.push(obj)
    }

    return r;
  }, [])
}

const result = toTree(data);
console.log(result)

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

The success method in the observable is failing to trigger

Could someone explain why the () success method is not triggering? It seems to be working fine when using forkjoin(). Shouldn't the success method fire every time, similar to a final method in a try-catch block? Note: Inline comments should also be c ...

Error message "Undefined reference" occurs while utilizing an array of pointers

My task involves utilizing a pointer of a pointer as an array of pointers. Below is the code snippet I currently have: className **wordArray; wordArray = new className*[wordCount]; ifstream fileInput; fileInput.open(fileDir); while (fileInput >> wor ...

Is there a way to verify in AngularJS whether ng-model contains a string or a numerical value?

In my Angular application, I have written a JavaScript function that checks if the value of a text field is undefined or empty, and it is working properly. $scope.checkNumber = function(user_answer){ if(user_answer == undefined){ return false; } } My ...

What is the best way to retrieve information from this kind of JSON data?

Currently, I am attempting to extract the 'createddt' values from an array column called NOTES, which is of type json in a PostgreSQL table named USERS. [{"notes":"testing note 1","createdby":"fname1, lname1","createddt":"2018-09-05T13:28:32-07: ...

React Native error: encountering the error message "undefined is not an object '_this3.props.navigation()'"

I am encountering an error in the navigationOptions() function when running my React app, but everything is working correctly in the render() function. App.js import React, { Component } from 'react'; import { AppRegistry, View } from 'r ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...

Preventing toggle from altering the width of the side navigation bar

Is there a way to prevent the width of the side bar from changing when toggling the top level items in the side nav bar, especially if the sub navigation items are wider? Click on 'Click me' in the side nav item to see what happens. Check out th ...

Navigating the jQuery Search Form: Redirecting to Pages within your Website

After successfully creating my first Javascript search form with an Autocomplete Script, I am facing a challenge. I want to enable users to press "enter" after searching for a product and get redirected to the corresponding product URL page. The operation ...

Exploring the Distinctions among JavaScript Objects

Currently facing a challenging problem and in search of an efficient solution. I have two Javascript Objects structured as {id:data, id:data, ..} If we focus solely on the Keys, they appear like this: B = ["1","2","3"] A = ["2","3","4"] My goal is ...

I keep encountering an issue every time I try to use ng-repeat in my

I am using NG-repeat to display results. The information is retrieved from an array through an API call using $http.post. One of the items in the results is a 'Thumbnail'. A snippet of the result looks like this: "Thumbnail":"http ...

Is it possible to toggle all parent targets in Bootstrap?

When trying to showcase my point, I believe it is best demonstrated by visiting Bootstrap documentation at https://getbootstrap.com/docs/4.0/components/collapse/ and viewing the "multiple targets section." In this section, you will find three buttons: togg ...

Showcase PHP associative arrays specifically containing the key named 'name'

My title may seem a bit unclear, but I'm struggling to find the right words to describe it. Essentially, what I'm trying to convey with the term "array name" is exemplified in this code snippet: array (size=3) 'arrayname0' => ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

Unable to execute tests on angular example project

I recently cloned the Angular Material-Start project. According to the documentation: When I run npm run tests to start all my Karma unit tests, I encounter an error: npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\DevSoft\\Node ...

When a user clicks on a list item, a class is added to change the background color of that particular item while simultaneously removing the class from other list items

add image description hereI'm attempting to apply a class to the list item in an unordered list when clicked, while simultaneously removing the same class from the other list items. I've tried using the JavaScript logic below, but I'm not a ...

Activating a switch to execute a PHP code that displays a JavaScript code

At the conclusion of the button's click event, the following JavaScript code is executed: xmlObj.open ('GET', /ajax.php, true); xmlObj.send (''); } This will trigger the php script ajax.php located in the root directory: <?ph ...

The jQuery dialog() function is functioning properly on one page, but encountering issues on a different

On one of my web pages, I have successfully implemented a modal dialog using jQuery and jQuery UI. However, when I try to replicate the same setup on another page with identical HTML markup and JavaScript files, I encounter the following errors: Internet ...

Issue encountered while configuring server using express.js

Here is the server.js file I am working on, but I encounter a specific error when trying to set up the server with Express.js var express = require('express'); var app = express(); var PORT = process.env.PORT || 3000; app.all('/*', ...

Is it secure to use console.time() in a Node.js environment?

Looking at a small snippet of node.js code, here's what I have: console.time("queryTime"); doAsyncIOBoundThing(function(err, results) { console.timeEnd("queryTime"); // Process the results... }); Running this on my development system gives m ...

JavaScript allows you to set an expiration date for a specific item

I am facing an issue with a form that contains inputs. On clicking the submit button, I want to capture the current time and add 10 hours to it before updating the table cell named expdate. Although I have a function in place for this purpose, it seems to ...