How to extract the depth of a leaf node from a tree view using AngularJS

My tree view Json object looks like this:

{
  "Name": "Root",
  "Id": "-1",
  "ParentId": "null",
  "children": [
    {
      "Name": "Math",
      "Id": "1",
      "ParentId": "-1",
      "children": [
        {
          "Name": "Addition",
          "Id": "3",
          "ParentId": "1",
          "children": [
            {
              "Name": "Two Numbers",
              "Id": "5",
              "ParentId": "3",
              "children": []
            },
            {
              "Name": "Three Numbers",
              "Id": "6",
              "ParentId": "3",
              "children": []
            }
          ]
        },
        {
          "Name": "Substraction",
          "Id": "4",
          "ParentId": "1",
          "children": [
            {
              "Name": "Four Numbers",
              "Id": "7",
              "ParentId": "4",
              "children": []
            },
            {
              "Name": "Five Numbers",
              "Id": "8",
              "ParentId": "4",
              "children": []
            }
          ]
        }
      ]
    },
    {
      "Name": "English",
      "Id": "1",
      "ParentId": "-1",
      "children": []
    }
  ],
  "selected": "selected"
}

If I select the leaf node "Two numbers," mytree.currentNode.Name will only display "Two Numbers." However, I would like to show the full path from the root to the selected node: "Root / Math / Addition / Two Numbers." Is there a way to achieve this? Please provide assistance. Thank you in advance.

Answer №1

The decision you made with the design is causing difficulty in accessing the full depth.

There are two methods for storing hierarchical data: using references or IDs. It's best not to mix and match between them.

If you store a reference to the parent instead of a ParentID, you'll find it much easier to navigate through the entire tree.

Alternatively, if you opt for using parent IDs, consider using a dictionary of IDs and objects instead of nested children. This will allow for quick and easy traversal of the tree structure.

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

Regular expressions can be used to target a specific sentence that contains multiple words

With this regular expression, I am able to choose a sentence based on a single word: [^.]* word [^.]*\. Is there a way to select a sentence with two or more words conditionally? For instance, how would I go about selecting a sentence if word A and ...

PHP is capable of showing echo statements from the function, however it does not directly showcase database information

My current challenge involves using AJAX to pass the ID name of a div as a string in a database query. Despite being able to display a basic text echo from my function, I'm unable to retrieve any content related to the database. // head HTML (AJAX) $( ...

The image being displayed is significantly wider than the corresponding HTML element

I'm attempting to display this webpage in PNG format using npm's wkhtmltox: <!doctype html> <html> <head> <meta charset="utf-8"> <style> html, body { padding: 0; width: 340px; } ...

Tips for retrieving data in the parent component

Currently, I am utilizing Vue v1.0.28 and vue-resource to interact with my API and fetch the resource data. In this setup, I have a parent component named Role, which includes a child component named InputOptions. The foreach loop within iterates over the ...

Surprising outcomes arise when the results of Three.js EffectComposers are combined, as the Additive and Subtractive effects interact in unexpected

While working on postprocessing in Three.js with EffectComposers and shader passes, I encountered some unexpected behavior when combining the WebGLRenderTargets (renderTarget2) from different composers. My setup involves five composers: three to render sce ...

Adding participants using the Google Calendar API in JavaScript: A step-by-step guide

I am attempting to include attendees in a Google Calendar event using the API. The method I am currently using, similar to the update function, is not working as expected and is removing all previous attendees. Below is the code snippet: const attendees ...

What are the steps to activate the hot-swapping feature for HTML and JavaScript files in IntelliJ's Community edition?

Just starting out with IntelliJ to work on an AngularJS project with spring-boot as the backend server. Every time I make changes to my HTML or JavaScript code, I find myself needing to restart the app server. Is there a configuration setting or plugin ava ...

Changing letter cases in a textbox using Javascript

I have a challenge to create a code that can switch the case of text entered by the user. Here is what I currently have: var num; function toggleTextCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase( ...

DataTables.js, the powerful JavaScript library for creating interactive tables, and its compatible counterpart

I'm currently making some changes to a dynamic table that require enabling a vertical scroll bar. As a result, I need to implement this vertical scroll bar mechanism on an existing table. The code in our project utilizes dataTables.js version 1.5.2 ...

Attempting to authenticate user with Node.js and MongoDB integration

I have been attempting to log in a user, but I keep encountering the error "user is not defined". I've made sure to use both upper and lowercase variations of "user/User", yet it continues to show up as undefined. var mongoose = require("mongoose") va ...

Displaying Spinner and Component Simultaneously in React when State Changes with useEffect

Incorporating conditional rendering to display the spinner during the initial API call is crucial. Additionally, when the date changes in the dependency array of the useEffect, it triggers another API call. Question: If the data retrieval process is inco ...

Angular-UI keypress event allows users to interact with components and

I am facing challenges while using the keypress feature in the following code snippet- <div ng-controller="GBNController"> ... <input id="search-field" type="text" placeholder="JSON Query" ng-model="queryText" ui-keypress="{enter: foo()}"/> .. ...

AngularJS: Advanced Routing for Dynamic Web Applications

Hello, I am currently exploring the possibility of implementing something similar to this code snippet using AngularJS: $routeProvider .when('/root/:controllerName/blah/:blahId/blah/:blah', { templateUrl: '/tmpl/:controllerName ...

Generate permutations with a specified length parameter using a JavaScript permutation generator

Many generators I've come across create a squared matrix, assuming the output length based on the number of items provided. However, I'm looking for a solution where I can specify both the items and the desired length. It seems like such a simpl ...

Adding HTML to a webpage through the use of JavaScript's .innerHTML functionality

Currently in the process of creating a website template, I have made the decision to experiment with using an external JS file for inserting HTML at the top of the page to streamline navigation (eliminating the need for manual copying and pasting). My att ...

Preventing the occurrence of numerous ajax requests or halting ongoing requests

Currently, I am utilizing the flotchart plugin to track user interactions on a chart and retrieve additional information from a database based on the chart value. For instance, if a user hovers over a specific date like "24 May," an AJAX call is triggered ...

A collection of arguments in Restangular

Hey there, I've been working on passing filters to my getList method of Restangular. Here's what I have in my app: var filters = Filters.get(); var query = {}; for (var i in filters) { query['filters['+i+']'] = filters[i] ...

Exploring the Scope of React Functional Components

My current dilemma involves a React Functional Component acting as a video player. I'm facing an issue where I need to invoke a function named onEnded when the video player triggers its ended event. This function takes in two parameters: a callback pa ...

What is the best approach to convert text to uppercase or lowercase based on the length of the string in Angular version 1.5?

My goal is to apply text formatting to a string named 'name'. Once the string is entered into an HTML form and the save button is clicked, the new formatted string should be displayed below the form. The formatting rule states that if the length ...

Ways to access states from a Vuex store within a Vuetify list in VueJs

Here is a snippet from my Vue file: import store from '@/store' export default{ name: 'myList', data: () => ({ show: true, listContent: [{ name: '1', icon: 'pers ...