Tree Structure with updated ParentId and ChildId

Dealing with a JSON hierarchy tree that has multiple levels of nesting can be tricky. Trying to loop through this JSON data to display the tree structure in the UI often leads to cyclic redundancy issues, especially when the parent IDs are the same at different levels. To avoid getting stuck in an infinite loop, it is necessary to add unique identifiers for both the parentID and ID.

Here's a sample of the JSON:

[
  {
    "id": "12",
    "text": "Man"
  },
  {
    "id": "6",
    "parentId": "12",
    "text": "Boy"
  },
  {
    "id": "9",
    "parentId": "6",
    "text": "Boy-Boy"
  },
  {
    "id": "13",
    "parentId": "9",
    "text": "Boy-Boy-Boy"
  },
  {
    "id": "7",
    "parentId": "12",
    "text": "Other"
  },
  {
    "id": "6",
    "parentId": "7",
    "text": "Boy"
  },
  {
    "id": "9",
    "parentId": "6",
    "text": "Boy-Boy"
  },
  {
    "id": "13",
    "parentId": "9",
    "text": "Boy-Boy-Boy"
  }

Attempts have been made to add depth to each level, but maintaining the relationship between ParentId and Id has proven challenging.

var depthArray = []

function addDepth(arr, depth = 0) {
  arr.forEach(obj => {

  obj.id =  obj.id + '-' + depth;
  if(obj.children !== undefined) {
  addDepth(obj.children, depth + 1)
}})
return arr;
}

[
  {
    "id": "12",
    "text": "Man"
  },
  {
    "id": "6",
    "parentId": "12",
    "text": "Boy"
  },
  {
    "id": "9",
    "parentId": "6",
    "text": "Boy-Boy"
  },
  {
    "id": "13",
    "parentId": "9",
    "text": "Boy-Boy-Boy"
  },
  {
    "id": "7",
    "parentId": "12",
    "text": "Other"
  },
  {
    "id": "6-1",
    "parentId": "7",
    "text": "Boy"
  },
  {
    "id": "9-1",
    "parentId": "6-1",
    "text": "Boy-Boy"
  },
  {
    "id": "13-1",
    "parentId": "9-1",
    "text": "Boy-Boy-Boy"
  }
]

Answer №1

It seems that your recursive function is not working as expected. Have you considered this alternative approach?

'use strict';
function addDepth(arr, id, depth) {
  if(depth === undefined) depth = 0;
  if(id !== undefined)
    arr.forEach(obj => {

        if(id == obj.parentId) {
        if(depth) obj.parentId += '-' + depth;
        addDepth(arr, obj.id, depth + 1)
      }
    })
  else arr.forEach(obj => { addDepth(arr, obj.id, depth); });
  return arr;
}

console.log(addDepth(
[
  {
    "id": "12",
    "text": "Man"
  },
  {
    "id": "6",
    "parentId": "12",
    "text": "Boy"
  },
  {
    "id": "9",
    "parentId": "6",
    "text": "Boy-Boy"
  },
  {
    "id": "13",
    "parentId": "9",
    "text": "Boy-Boy-Boy"
  },
  {
    "id": "7",
    "parentId": "12",
    "text": "Other"
  },
  {
    "id": "6",
    "parentId": "7",
    "text": "Boy"
  },
  {
    "id": "9",
    "parentId": "6",
    "text": "Boy-Boy"
  },
  {
    "id": "13",
    "parentId": "9",
    "text": "Boy-Boy-Boy"
  }
]
));

The structure of the data and the output may differ, but here's a hypothetical visualization based on the code provided:

12          Man
12 6        Man Boy
12 6 9      Man Boy Boy-Boy
12 6 9 13   Man Boy Boy-Boy Boy-Boy-Boy
12 7        Man Other
12 7        Man Other Boy
12 7 6 9    Man Other Boy Boy-Boy
12 7 6 9 13 Man Other Boy Boy-Boy Boy-Boy-Boy

var data = GetData();
var arr = [data[0].text], parent;
for(var i=0;i<data.length;i++) {
    if(parent = data[i].parentId) {
        arr.push(data[i].text); 
        for(var j=i;j >= 0;j--) {
            if(data[j].id == parent) {
                arr.push(data[j].text); 
                if(data[j].parentId) {
                    parent = data[j].parentId;
                    j = i;
                }
            }
        }
    }
    console.log(arr.reverse().join(" -> "));
    arr = [];
}

function GetData() { return [
    {
      "id": "12",
      "text": "Man"
    },
    {
      "id": "6",
      "parentId": "12",
      "text": "Boy"
    },
    {
      "id": "9",
      "parentId": "6",
      "text": "Boy-Boy"
    },
    {
      "id": "13",
      "parentId": "9",
      "text": "Boy-Boy-Boy"
    },
    {
      "id": "7",
      "parentId": "12",
      "text": "Other"
    },
    {
      "id": "6",
      "parentId": "7",
      "text": "Boy"
    },
    {
      "id": "9",
      "parentId": "6",
      "text": "Boy-Boy"
    },
    {
      "id": "13",
      "parentId": "9",
      "text": "Boy-Boy-Boy"
    }
];
}

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

What's preventing me from using just one comparison condition in TypeScript?

The issue at hand is quite simple: An error occurred because I tried to compare a number with a 'Ref<number>' object. It seems ridiculous that I can't compare two numbers, but as I am new to Typescript, I would greatly appreciate some ...

Is it possible to conceal JavaScript comments on a page before it is displayed?

Curiosity has led me to ponder a question that may seem trivial. Consider this scenario: in my HTML or ASPX page, I include a comment for some JavaScript code. When the page loads, will the comments be rendered along with the rest of the page's conten ...

Arrange the elements in a column of a multi-dimensional array in descending order while maintaining their respective keys

I have an array that needs to be sorted based on the 'answer' value in each 'scores' array, from high to low. $array = [ 503 => [ 'scores' => [ 4573 => ['answer' => 100], ...

How to eliminate the ng-component tag from an Angular 8 table row template

I currently have a dynamic table component with 2 modes: Normal table - functioning properly Custom Row Template - encountering issues due to Angular adding the <ng-component> tag The logic within the TableComponent is not the main concern, it&apo ...

Issue communicating with connect-flash: flash variable is not recognized

I've been diving into books on node.js, express, and mongodb lately. In one of the examples, the author showcases the usage of connect-flash. However, I'm encountering some difficulties getting it to function as expected. Below are snippets from ...

Condense categories

Hello there, I'm currently working on a table that contains different groups, and I am trying to figure out how to collapse categories within my table. Check out the Plunker here This is the HTML code snippet I am using: <table border=1> ...

Storing JSON data in SQL Server

Is there a way to eliminate spaces using the given query? The second input value (" DEF") and third input value ("GHI ") contain extra spaces. How can we remove these spaces? Here is the original query: SELECT * FROM openjson('[{"value":"12 ...

Set onfocus for DOM elements dynamically

I have a question regarding assigning onfocus or similar functions to DOM elements during runtime. Here is the scenario: <input type="text" id="box" onfocus="inputFocused()"/> Now, in a runtime assignment case: <input type="text" id="box"/> ...

How to utilize JSON for decoding information in PHP

I am in need of decoding this Json using PHP, but I am not sure how to do it. I have looked at the function on php.net/json, but it does not provide instructions on how to decode this specific type of data. {"c":[{"v":"0","e":"","n":"45","cc":"PSDB - PT ...

Mongooses, Callbacks, and Bears, oh my! I'm having trouble accessing the values

Greetings everyone, I find myself stuck in a callback nightmare while attempting to retrieve basic values from a Mongoose count by passing a {query}. Although I can access the value and see it fine in the console within the callback, extracting it from an ...

Guidelines for Sorting Objects and Arrays in a JavaScript Array

I have a set of data that needs to be filtered based on specific parameters. While I can successfully filter through the initial value in the array, I am struggling to filter deeper into nested arrays. The dataset is structured as follows: let data = [ ...

Transform XML to JSON using Node.js and send the converted data back to the Frontend

Currently, I am faced with the task of converting XML data into JSON format so that I can send it back to my Angular application. Despite successfully retrieving the data, I am struggling with the conversion process and returning it to Angular. To handle t ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

Ensuring that EJS IF/ELSE statements are evaluated accurately

I am encountering an issue where my variable 'answer' is returning the string 'success' and displaying correctly in the view. However, the IF/ELSE statement always seems to evaluate to the ELSE condition and displays 'no' inst ...

The curious case of unusual behavior in jQuery's livequery() method

When attempting to use the jQuery plugin "livequery" to highlight certain words within dynamically generated search results, the highlighting does not appear to work! Strangely, adding an alert() function before executing the code causes the highlighting ...

Refresh Vue/Nuxt Components Fully

Understanding how this.$forceUpdate() functions, I am not simply looking to re-render the component. In Nuxt applications, page components have asyncData() as a lifecycle method that runs before created(). I utilize this method to retrieve initial data an ...

Perform mean subtraction on an array of double values in C++

Currently, I have an array of double* containing approximately 10,000 elements that require subtraction of the mean value quite frequently. My current method for this task is not very efficient: double mt = 0; for (int i=0; i<n; i++) {mt += array[i];} ...

The collaboration of Nodemon and Redwood-Broker

I have been running Nodemon in my express app without any special configuration. In my package.json file, I only have the following: "scripts": { "start:dev": "nodemon app/app.js" } ... Everything runs smoothly until I make changes and Nodemon attempts ...

Manipulate geojson objects based on criteria in Python to add or remove data

I am dealing with a Geojson structure that looks like this: data = { "type": "FeatureCollection", "name": "entities", "features": [ { "type": "Feature", "properties": { "Layer": "0", "S ...

Having trouble displaying the desired formatting when mapping through nested JSON in Node ES6

Currently working on a project to build a photo gallery using nested JSON data. My goal is to iterate through the data and create a well-structured JavaScript object or a smaller JSON file that includes only the text and image URL nodes. However, my curren ...