Arranging an array of objects by their unique identifiers

Given an array of objects containing root and list elements in a tree structure, how can I efficiently organize them into a tree with an unknown depth? Each object has a parent element ID property.

I am currently working on building a menu. While I have successfully organized list elements under their respective parents, I am facing difficulties organizing all root elements without nesting loops to check if everything is properly structured.

Here is an example of the initial data: https://pastebin.com/eCSZ1HgR

[
    {
     "groupId": 1,
     "parentGroupId": null
    },
    {
     "groupId": 3,
     "parentGroupId": 1
    }, ...
]

If an object's parentGroupId is null, it indicates that it belongs to the root of the tree.

Below is the code snippet I am currently using:

for (var i = 0; i < groups.length; i++) {
  var childGroup = groups[i];

  if (childGroup.parentGroupId === null) {
    continue;
  }

  for (var j = 0; j < groups.length; j++) {
    var parentGroup = groups[j];

    if (childGroup.parentGroupId === parentGroup.groupId) {
      if (parentGroup.hasOwnProperty('children')) {
        parentGroup.children.push(childGroup);
      } else {
        parentGroup.children = [childGroup];
      }

      break;
    }
  }
}

Answer №1

Utilizing Array.prototype.reduce and Array.prototype.filter functions makes this task very straightforward.

const treeStructure = groups.reduce((accumulator, currentGroup) => {
  currentGroup.children = groups.filter(group => group.parentGroupId === currentGroup.groupId);
  accumulator.push(currentGroup);
  return accumulator;
}, []).filter(group => group.parentGroupId === null);

Answer №2

Below is a method that accomplishes a deep-copy operation:


const sampleData = [
    {
     "groupID": 1,
     "parentGroupID": null
    },
    {
     "groupID": 3,
     "parentGroupID": 1
    },
    {
      "groupID": 4,
      "parentGroupID": 3
    },
    {
      "groupID": 5,
      "parentGroupID": 1
    }
];

function convertFlatToTree(flatArray, idKey, parentKey, childrenKey) {

    const treeList = [];
    const indexMap = {};

    /* Cloning the array and building an index */

    flatArray.forEach(item => {
      const clonedItem = Object.assign({}, item);
      treeList.push(clonedItem);
      indexMap[item[idKey]] = clonedItem;
    });

    /* Assigning children nodes */

    treeList.forEach(item => {
      if (item[parentKey]) {
        const parentItem = indexMap[item[parentKey]];
        if (Array.isArray(parentItem[childrenKey])) {
          parentItem[childrenKey].push(item);
        } else {
          parentItem[childrenKey] = [item];
        }
      }
    });

    /* Selecting root elements */

    return treeList.filter(item => item[parentKey] === null);
}

const outputData = convertFlatToTree(sampleData, "groupID", "parentGroupID", "children");

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

Encountering an issue with undefined ID when utilizing a radio input field in Vue JS

I'm facing an issue and I hope you can assist me with it. My webpage contains Vue scripts and a list of radio selections rendered via Liquid tag and GraphQL results. The problem arises when I click the submit button or select a radio option, resultin ...

Is there a way to set a personalized callback function when closing a modal with MicroModal?

I've been utilizing MicroModal for showcasing a modal window. Everything seems to be working smoothly, except for when I try to trigger an event upon closing the modal. It's unclear to me where exactly I should implement this callback function. ...

Error message in Angular 9: "The 'pipe' property is not recognized on the 'void' type"

I recently created a function for streaming audio in Angular: private streamObservable(url) { new Observable(observer => { // Play audio this.audioObj.src = url; this.audioObj.load(); this.audioObj.play(); const handl ...

The Laravel 8 send:notification command is throwing an error due to an undefined array key "id"

My goal is to send a notification to all users enrolled in an event one day before the event's start date. Within my database, I have a user table and events table that both store important information such as event start dates. Additionally, there is ...

Sending a JavaScript click event using curl and PHP

Attempting to extract information from a website. The main page contains multiple option buttons along with an ACCEPT and RESET button. When the user selects options and clicks on the ACCEPT button, new content is displayed. I have a question regarding ma ...

The impact of THREE.OrbitControls on the rotation of objects in the scene

Recently started diving into THREE.js and I've put together a simple scene with the basics: http://codepen.io/inspiral/full/Lewgj Overall, everything is running smoothly aside from an odd glitch that's been happening due to the new mouse event h ...

Is there a way to create a universal script that works for all modal windows?

I have a dozen images on the page, each opening a modal when clicked. Currently, I've created a separate script for each modal. How can I consolidate these scripts into one for all modals? <!-- 1 Modal--> <div class="gallery_product col-lg-3 ...

Guide on using javascript to alter a json structure

Recently, I discovered a method to manipulate a JSON file using JavaScript. Although I don't have any formal training in JavaScript, I understand that it is primarily utilized on web browsers. Can someone guide me on how to execute this script? I cons ...

Angular project icons not displaying in the browser

My current project in Angular was functioning properly until recently. I am facing an issue where the images are not being displayed on the browser when I run ng serve, resulting in a 404 error. Interestingly, everything else seems to be working fine witho ...

Unable to save Ajax data in session array

Currently, I am developing a cart system using jquery, ajax, and php. The issue I am facing is that the text within the HTML elements is not being added to the session array. Below is the ajax code I am using: $(document).ready(function(){ $("#car ...

What is the reason behind react-router-dom not supplying location.key during the initial page load?

In my component screen using react-router, I heavily rely on the parameter location.key to identify paths and other elements (using location.pathname did not resolve the issue). However, I noticed that when I first load my app, react-router does not have ...

Polymer: Basic data binding is not functional in the second element

After dedicating 6 hours to this problem, I still can't seem to find a solution. Below is the code snippet from index.html: <flat-data-array availableModes="{{modes}}" id="dataArray"></flat-data-array> <flat-strip-view availableModes=" ...

Encountered Minified React error #418 and #423 while using Next.js v12.3.1 and React v18.2.0

Ever since the recent updates, I've been facing a couple of errors in my application that go like this: Uncaught Error: Minified React error #418; visit https://reactjs.org/docs/error- decoder.html?invariant=418 for the full message or use the non-mi ...

The lookAt method in THREE.js is not functioning properly when called after the rendering process

The code snippet below seems to be causing some issues. It requires jquery and three.js to function properly. The problematic lines are as follows: // change the view so looking at the top of the airplane views[1].camera.position.set( 0,5,0 ); views[1].ca ...

Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code: window.addEventListener("beforeunload", function(event) { $.ajax({ url: api ...

The error message: "Trying to access property 'get' of an undefined object"

$http.get('/contactList'). success(function(data){ console.log('received data from http get'); }). error(function(data) { $scope.error = true; $scope.data = data; return 'error message'; }); There seems to be ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

What could be causing certain javascript functions to not work properly?

Currently, I am using JavaScript and AJAX to validate a registration form. The functions restrict(elem) and checkusername() are both working as intended. When the AJAX passes the checkusername variable to PHP, it checks if the username exists and displays ...

Troubleshoot the pattern of Pascal's Triangle

Can someone help me understand what's wrong with my implementation of Pascal's Triangle in JavaScript? I came across a similar thread discussing recursion, but I'm having trouble figuring out the errors in my code. I would appreciate fresh e ...

Issue with React submit button for posting data is not functioning as intended

My dilemma lies within a Modal component containing a Form and Button. The goal is to trigger a POST request (managed in a separate file) upon the user clicking the button, which will run a simulation using the validated input values. Surprisingly, the onC ...