Transformation of data structures

Is there a way to transform the array structure that represents parent-relation into a 2D array format?

const array = [{id: 1, parentId: 2}, {parentId: null, id: 2}];

The goal is to create a new array where the first element of each nested array is the parent with no parentId specified, and the last element is always the child or leaf element.

For example:

const array_2 = [
  [{ id: 1, parentId: null}, { id:2, parentId: 1 }, { id: 3, parentId: 2}], [...], [...]
]

Answer №1

It seems like you are interested in obtaining the paths from the starting point of the tree to each individual node:

const nodes = [
  {id: 1, parentId: 6},
  {id: 2, parentId: 1},
  {id: 3, parentId: 4},
  {id: 4, parentId: 6},
  {id: 5, parentId: 1},
  {id: 6, parentId: null}, // Root
  {id: 7, parentId: 2},
];

const nodeMap = new Map(nodes.map(node => [node.id, node]));
const paths = nodes.map(node => {
  const path = [{...node}]; // Or: const path = [node];
  let parentId = node.parentId;
  while (parentId !== null) {
    const parentNode = nodeMap.get(parentId);
    if (parentNode === undefined) {
      throw new Error(`No node exists with ID ${parentId}`);
    }
    path.unshift({...parentNode}); // Or: path.unshift(parentNode);
    parentId = parentNode.parentId;
  }
  return path;
});
console.log(paths);

This is the layout of the tree that was utilized in the provided code snippet:

https://i.sstatic.net/fuMqQ.png

The paths from the root to each node are displayed as follows:

Node-1: 6 <- 1
Node-2: 6 <- 1 <- 2
Node-3: 6 <- 4 <- 3
Node-5: 6 <- 1 <- 5
Node-6: 6
Node-7: 6 <- 1 <- 2 <- 7

The outcome produced by my script is a JavaScript array presented in two dimensions.

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

Transitioning JavaScript plugins to Vue framework

Recently, I've been transitioning my PHP app to Vue 3 in order to enhance the interactivity of the site. In the past, we utilized JS plugins that were triggered by selectors to carry out various tasks like generating forms and loading videos. However ...

Using ajax to call the Google Maps Api is proving to be ineffective

I am facing some issues with a website. On this particular webpage (), I am trying to display a Google map on the location page using an AJAX function. The getLocation.php file is being called by AJAX: <?php echo '<div id="map-canvas"></ ...

Is there a way to achieve a similar outcome on my site?

Recently, I noticed a mouse-hover effect on two websites and found it quite appealing. https://i.sstatic.net/Ly0gP.png https://i.sstatic.net/oDe1i.png This is the specific effect that caught my attention. Can anyone provide me with insight on how to impl ...

Fill an array with the column indexes that match a specific set of strings

My goal is to fill a 2-Dimensional Variant Array with a group of strings and their corresponding column numbers (Positions) from different worksheets. To achieve this, I have created an intermediate procedure that transfers the values from each worksheet ...

The functionality of PHP in relation to the jQuery post feature seems to be malfunction

After developing the JavaScript functionality for this contact form, below is the HTML structure without any CSS styling included: <!-- Contact Form --> <div class="cws-widget"> <div class="widget-title" style="color:#fec20b;">S ...

Customizing buttons on Dialogs in JavaScript to have dynamic names

There is something on my website that resembles this: $("#id").html(msg2show).dialog({ //Other attributes buttons: { "Yes": function() {//Code}, "No": function() {//Code} } ...

I encountered the error message "TypeError: e is undefined" while attempting to make an ajax call

My goal is to showcase a website's content using file_get_contents in a PHP script and ajax on the front-end. I am able to display the entire page successfully, but when attempting to only show a certain number of images, I encounter the "TypeError: e ...

After combining two files in browserify, the error message "XXX.foo is not a function" appeared

When using browserify to bundle two JavaScipt files into one with the command: browserify X1.js X2.js --standalone XXX > bundle.js The file X1.js contains a function like this: function foo() { console.log("something") } And it is being exported i ...

Data not displaying in Vuetify table

Can someone help me with a table display issue in Vuetify? I've tried various solutions but my data is not showing up on the table, although I can see it using the dev tools. Here's a screenshot of how the data looks in the dev tool I've s ...

Can you please provide the Jquery alternative to this?

Can you provide a sleek jQuery solution for this problem? $('A').append(str); ...

What is the method to utilize the process.env object from within an imported npm package in the importing class?

In my React app, I used dotenv to set process.env variables for each component. When all components were in the same source code repo and imported via '../component/component_name', accessing these variables was easy using process.env.variable_na ...

Tips on showing database information with JavaScript

<script type="text/javascript"> var content = { metadata: ['January', 'February', 'March', 'April'], infoSets: [ { fillColor: "rgba(220,220,220,0.2)", strokeCol ...

Monitor the collection for changes before adding an item to the collection

When using ui-select multiple, I am facing an issue where I need to check the collection before ng-model="collection" is updated in order to ensure that the new value is not already present in it. Simply watching the collection does not solve this problem ...

retrieving an array of checkbox values using AngularJS

As a beginner in Angular, I have been struggling to implement a feature where I can add a new income with tags. I have looked at similar questions posted by others but I still can't get it to work. The tags that I need to use are retrieved from a ser ...

Understanding byte sequences as unsigned integer shorts in Python

I am faced with the task of interpreting 16 bytes received via a TCP socket as 8 unsigned shorts. The following line effectively retrieves the data (the 16-bit values of 8 analog-to-digital converters), allowing me to access each byte by index in a byte a ...

The interlocking web of Angular dependencies

Can I begin my angular module without specific dependencies? This is my angular.module. angular.module("app", [ 'ngSanitize', 'ngAnimate', 'ui.router', 'ngMaterial', 'ngRoute', 'ngCookies', &a ...

A helpful guide on performing a service call in AngularJs when attempting to close the browser tab or window

I am currently working on implementing a service call that will trigger when the browser tab or window is being closed. I was wondering if there is a way to make a RestApi call when attempting to close the browser tab or window. Does anyone have any sugge ...

Incorporating Bootstrap Navbar into a create-react-app project

I recently created a new project using create-react-app. To incorporate Bootstrap into my project, I followed these steps: npm install --save bootstrap@3 Next, I imported Bootstrap in my root file index.js: import 'bootstrap/dist/css/bootstrap.css& ...

Tips for automatically closing a Bootstrap 3 modal when AJAX request succeeds?

I'm trying to close a modal upon ajax success, but I'm encountering an issue. Here is my code snippet: Javascript success: function() { console.log("delete success"); $('#deleteContactModal').modal('hide'); $( "# ...

Encountered an error while attempting a GET request to 'http://localhost:3000/': The resource failed to load, resulting in a net::ERR_CONNECTION_REFUSED error in delete.js

Every time I attempt to GET '/' through my express server, I encounter an error message indicating "Failed to load resource: net::ERR_CONNECTION_REFUSED ... delete.js". This issue typically arises when I try to submit a form from http://localhost ...