Locate the parent and child elements within an array

Within the array provided below, there are parent items as well as children.

I am currently able to identify parents (depth 0) and their immediate children (depth 1), however I am unsure how to handle deeper nested levels.

For reference, you can view the fiddle here: http://jsfiddle.net/s3x5f4ap/2/

const comments = [
  { "depth": 0,"id": "f35vz2f"},
  { "depth": 0,"id": "f359354"},
  {   "depth": 1,"id": "f35e0b0", "parent_id": "f359354" },
  {     "depth": 2, "id": "f35ji24", "parent_id": "f35e0b0"},
  {     "depth": 2, "id": "f35rnwb", "parent_id": ""},
  {     "depth": 2, "id": "f35ojh4", "parent_id": "f35e0b0" },
  {       "depth": 3, "id": "f35lmch", "parent_id": "f35ji24"},
  {       "depth": 3, "id": "f35kl96", "parent_id": "f35ji24"}]

const parent = comments.filter(cm => cm.depth == 0);
final = [];
final = parent;

comments.forEach(a => {
  final.forEach(c => {
    if (c.id == a.parent_id) {
      c.child = []
      c.child.push(a);
    }
  })
})

console.log(final)

Answer №1

To create a tree structure, you can gather all connections between the nodes.

var data = [{ depth: 0, id: "f35vz2f" }, { depth: 0, id: "f359354" }, { depth: 1, id: "f35e0b0", parent_id: "f359354" }, { depth: 2, id: "f35ji24", parent_id: "f35e0b0" }, { depth: 2, id: "f35rnwb", parent_id: "" }, { depth: 2, id: "f35ojh4", parent_id: "f35e0b0" }, { depth: 3, id: "f35lmch", parent_id: "f35ji24" }, { depth: 3, id: "f35kl96", parent_id: "f35ji24" }],
    tree = function (data, root) {
        var t = {};
        data.forEach(o => {
            Object.assign(t[o.id] = t[o.id] || {}, o);
            t[o.parent_id] = t[o.parent_id] || {};
            t[o.parent_id].children = t[o.parent_id].children || [];
            t[o.parent_id].children.push(t[o.id]);
        });
        return t[root].children;
    }(data, undefined);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To create a tree-like structure, follow this approach:

var data = [{ depth: 0, id: "f35vz2f" }, { depth: 0, id: "f359354" }, { depth: 1, id: "f35e0b0", parent_id: "f359354" }, { depth: 2, id: "f35ji24", parent_id: "f35e0b0" }, { depth: 2, id: "f35rnwb", parent_id: "" }, { depth: 2, id: "f35ojh4", parent_id: "f35e0b0" }, { depth: 3, id: "f35lmch", parent_id: "f35ji24" }, { depth: 3, id: "f35kl96", parent_id: "f35ji24" }];
var attach_children_to_item = function (item, data) {
    item.children = data.filter(x => x.parent_id == item.id)
                        .map(x => attach_children_to_item(x, data));
    return item;
};
var tree = data.filter(x => x.depth == 0)
               .map(x => attach_children_to_item(x, data));
console.log(tree);

Keep in mind that there may be missing items if the depth is greater than 0 and the parent_id does not match another item.

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

How can the AngularJS model be updated while using long polling with Ajax?

How can I update the model using ajax long polling method? To start, I will load the default list: For example: - id1 - id2 - id3 Next, I set up an ajax long polling process in the background that runs every 5 seconds. When the ajax call receives an upd ...

Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked: $('li').click(function() { $(this).toggleClass('active'); }); My goal is to hide all other li elements in t ...

Verifying if a number is present in a textbox when inserting text (without using setTimeout)

I have an input field similar to the one shown below: <input type ="number" id="numberTxt" placeholder="Number Only"/> To ensure that the value entered is a number, I am using the following function with the keypress event: <script> ...

Querying data in Postgresql 9.4 using the JSONB data type based on a specified date

Transitioning from Mongodb, I am exploring how to select by range using jsonb type. I have approximately 2,880,000 records per day and need to query the database based on station and date fields. While I understand how to select by time range: SELECT * FR ...

Verify authentication on a SignalR console application using a JavaScript client

Here is the scenario and solution I am currently working on: In project one, I have a SignalR console application that handles the logic, including authentication using Entity Framework to query the database. In project two, I have an ASP.Net web applicat ...

Efficiently transferring multiple objects to a webservice through CXF services using JSON

I am working with a web service that accepts three different types of objects. I need to pass these objects using JSON and receive them on the server side as JSON. In this case, I convert the objects into Java objects. Is there anyone who can provide me w ...

Step-by-step guide to accessing the detail view upon selecting a table row in react.js

In my project, I have a table with multiple rows. When a row is selected, I want to display detailed information about that particular item. To achieve this functionality, I am utilizing react-router-dom v6 and MUI's material table component. Here is ...

How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way Code : var arr = ['1','2556','3','4','5']; ... ... var output = ` <scr`+`ipt> window.stringArray = [`+ arr +`] & ...

Permanently dismiss Bootstrap 4 alert using a cookie

Recently, I came across a bootstrap 4 alert that I found quite useful. Here is the code snippet for it: <div class="alert alert-warning alert-dismissible fade show" role="alert"> <button type="button" class="clo ...

Load data from a file into a dropdown menu using node.js

Exploring the realm of front end development on my own has been quite a challenge. I am currently struggling with the concept of populating a drop down box with data from a file. While utilizing node and JavaScript, I have decided to stick to these techn ...

JavaScript program that continuously reads and retrieves the most recent data from a dynamically updating JSON file at regular intervals of every few seconds

I am a beginner in JavaScript and I'm facing an issue with displaying the most recent values from a .json file on an HTML page. The file is updated every 10 seconds, and I am also reading it every 10 seconds, but I'm not getting the latest data. ...

The audio must start playing prior to being forwarded to a new page

As I delve into the world of website development on my own, I have encountered an interesting challenge. At the top of my webpage, I have embedded an audio file within a button. If the user chooses to mute the audio, the navigation links will remain silent ...

Learning to implement $first in an Angular ng-repeat to dynamically add a new table row

I am currently facing an issue with displaying a Google map for addresses in my Angular application. The problem seems to be related to the asynchronous nature of HTML and JS, but I am struggling to find a solution. The issue is that even though the map vi ...

Managing data in a database on Discord using JavaScript to automatically delete information once it has expired

Recently, I implemented a premium membership feature for my discord bot. However, I encountered an issue where the membership time starts counting down before the intended start time. To resolve this, I am looking to automatically delete the data from the ...

An effective way to prevent right-clicking on iframes across all websites

I am facing an issue with disabling right click for the iframe. I've successfully disabled it for the default URL of the IFrame, but when displaying any other webpage, the right click remains usable. Below are the sample codes I have used: document.o ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

Steps for inserting an additional header in an Angular table

https://i.stack.imgur.com/6JI4p.png I am looking to insert an additional column above the existing ones with a colspan of 4, and it needs to remain fixed like a header column. Here is the code snippet: <div class="example-container mat-elevation-z8"> ...

Help needed with PHP, MYSQL, and AJAX! Trying to figure out how to update a form dynamically without triggering a page refresh. Can anyone

Hey there! I'm fairly new to the world of dynamically updating databases without needing a page refresh. My goal is to build something similar to The end result I'm aiming for includes: Dynamically generating fields (Done) Loading existing dat ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

The function slice is not a method of _co

I'm attempting to showcase the failedjobs array<any> data in a reverse order <ion-item *ngFor="let failjob of failedjobs.slice().reverse()"> An issue arises as I encounter this error ERROR TypeError: _co.failedjobs.slice is not a fu ...