Guide to organizing a JavaScript object using a parent-child tree structure

Below is the JavaScript Object structure that I currently have:

[  
   [  
      null,
      "A"
   ],
   [  
      "A",
      "B"
   ],
   [  
      "A",
      "C"
   ],
   [  
      null,
      "D"
   ],
   [  
      "D",
      "E"
   ],
   [  
      "D",
      "F"
   ],
   [  
      "B",
      "G"
   ]
]

I am looking to rearrange it into the following structure:

[
   {

      parent: "A",
      child : [
         {
            parent : "B",
            child : [
               {
                  parent : "G"
               }
            ]

         },
         {
            parent : "C"
         }
      ]

   },
   {

      parent: "D",
      child : [
         {
            parent : "E"

         },
         {
            parent : "F"

         }
      ]

   }
]

Answer №1

To easily add parents in the result tree, simply follow a direct approach. However, for adding children, recursion is required. See the solution below:

var result_tree = [];
var test_data = [  
   [  
      null,
      "A"
   ],
   [  
      "A",
      "B"
   ],
   [  
      "A",
      "C"
   ],
   [  
      null,
      "D"
   ],
   [  
      "D",
      "E"
   ],
   [  
      "D",
      "F"
   ],
   [  
      "B",
      "G"
   ]
];

function create_tree(test_data) {
  test_data.forEach(function (node) {
    if (node[0] === null) {
      result_tree.push(
        {
          parent: node[1],
        }
      )
    } else {
      search_and_attach_child(result_tree, node[0], node[1]);
    }
  });
}

function search_and_attach_child(tree, parent, child) {
  if (!tree) {
    return;
  }
  tree.forEach(function (node) {
    if (node.parent === parent) {
      if (node.child) {
        node.child.push({parent: child})
      } else {
        node.child = [{parent: child}]
      }
    } else {
      search_and_attach_child(node.child, parent, child);  
    }
  })
}

create_tree(test_data);
console.log(JSON.stringify(result_tree));

Answer №2

Here is some code that might be useful for you:

var a = [  
   [  
      null,
      "A"
   ],
   [  
      "A",
      "B"
   ],
   [  
      "A",
      "C"
   ],
   [  
      null,
      "D"
   ],
   [  
      "D",
      "E"
   ],
   [  
      "D",
      "F"
   ],
   [  
      "B",
      "G"
   ]
];

var result = [];

for(var iter = 0; iter < a.length; iter++){

  var ele = a[iter];

  // check if element has no parent
  if(!ele[0] || !getParentByName(result,ele[0])){
    result.push({ parent: ele[1]});
  }
  // check if element has a parent
  else if(ele[0] && getParentByName(result,ele[0])){

    var parent = getParentByName(result,ele[0]);

    if(!parent.child) parent.child=[];

    parent.child.push({ parent: ele[1]});

  }

}

function getParentByName(result,name){

  for(var p=0; p <result.length;p++){

    if(result[p].parent == name) return result[p];

    for(var c=0; result[p].child && c <result[p].child.length;c++){
      if(result[p].child[c].parent == name) return getParentByName(result[p].child,name);
    }

  }

}

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

Searching for the closest array using C++

For my assignment, I am required to create an array with 5 random values, prompt the user to input a number for searching, and then display the index of the searched number. While this task seems relatively straightforward (and I have managed to do it), no ...

Confirmation of numerous checkbox selections

I am facing a challenge with a form that contains multiple questions answered through checkboxes. I need to validate that at least one checkbox is selected in all the questions, otherwise an alert message should pop up. Is it possible to achieve this val ...

Converting a JavaScript array into JSON using PHP

After analyzing the text, I was trying to figure out how to convert it into json format using php's json_decode function. Unfortunately, when I used json_decode on this text, it returned a syntax error. $arr = json_decode($str, true); {1: {name: &ap ...

Click the navigation bar to toggle it on and off

I have a script that creates a navbar. Currently, the dropdown menu only opens when hovered over. The issue arises when accessing this on a mobile browser, as the dropdown menu does not open. How can I modify this script to make the dropdown menu open wh ...

Unable to get Bootstrap tooltip functionality to work with jquery.slim when importing through webpack

After installing bootstrap 4.6.0 and jquery 3.6.0 via npm, I encountered a strange issue when trying to use tooltips. The following code snippet is functioning correctly: import jQuery from "jquery/dist/jquery"; import "bootstrap/dist/js/bo ...

Execute a jQuery ajax request to a specific variable

For my Phonegap/Cordova project, I have implemented functions to handle all ajax calls in the following way: function requestData(action, id ) { var data = { user_id: localStorage.getItem('user_id') }; if( action == 'fee ...

Invoking a SOAP service method defined by a message contract in soap.js

I am currently working with a soap service that utilizes message contracts. According to the rules of message contracts, both the request and response messages must be objects. Message contracts are essential for me because they provide complete control ov ...

When implementing the Parse Client Key in an Angular application, it may lead to encountering

I have been working on retrieving a class from Parse using a client key with the GET method. Successfully sent a request through Advanced Rest Client for Google Chrome by including X-Parse-Application-Id and X-Parse-Client-Key headers. [edit] [edit2] Resp ...

Performing an ajax call to trigger JavaScript with specified parameters and retrieving the response, all within a

I'm a bit confused here. I need to use node.js (node-webkit) locally, without PHP to wait for a response. Just JavaScript code and files. My goal is to make an AJAX call with parameters (I haven't decided on using GET or POST yet) to a "url" of ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

What is the best way to access an element's sibling using JQuery within a function?

How can I use JQuery to set an element to match the value of its sibling? In a table with multiple fields, when clicking an Edit button, I want to copy the label value to its adjacent input field: <table style="width:90%"> <tr> <td&g ...

What is preventing the audio from playing in Safari?

Recently, I developed a small JavaScript program that is meant to play the Happy Birthday tune. This program utilizes setInterval to gradually increase a variable, and depending on its value, plays or pauses certain musical notes. However, I encountered ...

Retrieve items within an array of objects in MongoDB using an array of IDs (using the $in operator in aggregation)

In my MongoDB database, I have a collection of stores [ { "_id" : ObjectId("6043adb043707c034d5363b7"), "shopId" : "shopid1", "appId" : "777", "shopItems" : [ { ...

Using an iframe containing a link to trigger the opening of a colorbox in the

Recently, I encountered a challenge regarding an iframe containing a bar graph. I wanted to achieve that when the graph is clicked, it would open a colorbox with a more detailed graph from the "PARENT" of that iframe. Initially, I managed to get the ifram ...

Sending an associative array to Javascript via Ajax

Learning a new programming language is always a great challenge. Can someone guide me on how to efficiently pass an associative array to JavaScript using AJAX? Below is a snippet of code from server.php: $sql = "SELECT Lng, Lat, URL FROM results LIMIT ...

Error in jQuery when element is not found

On my website, I use multiple jQuery functions, but not all of them are necessary on every page. These functions are all located in one XXX.js file, such as: jQuery(function() { $(".title").slug({ slug:'slug', hide: false }); }); ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

Is it possible to identify iOS Safari exclusively without including iOS Chrome, Firefox, and other browsers in the filter?

For those familiar with working on iOS web applications, it's known that Apple's policy causes Chrome and other mobile browsers on iOS to use an outdated javascript engine. Because of this, we need to disable certain rendering for Chrome and othe ...

Capture a fragment of a scene and convert it into a unique texture using THREE.JS

I'm interested in creating a texture of a specific area in my scene, similar to the example shown in the official documentation for three.js framebuffer here. As I examine the code provided, there's one particular aspect that's unclear to me ...

Using async and await inside a setTimeout function within a forEach loop

Currently, I am facing a challenge with scheduling background jobs in Node.js. I need each job to run only after the previous one has finished. Below is the code snippet inside a function: jobArray.forEach((item, i) => { setTimeout(async () => { ...