Navigating through a multidimensional array in Angular 2 / TypeScript, moving both upwards and downwards

[
  {id: 1,
  name: "test 1",
  children: [
               {id: 2,
               name: "test 1-sub",
               children: []}
            ]
}]

Imagine a scenario where you have a JSON array structured like the example above, with each element potentially having child elements up to nine levels deep.

If you find yourself exploring this tree structure and need to navigate both up and down the hierarchy, it's straightforward to move down by selecting child elements based on their index. But what about moving back up the tree?

One approach could involve keeping track of two key elements on the page: the main array containing all the data and an indicator showing your current position within the array.

codes: any = [];
currentCode: any = {};

To streamline readability and navigation, consider displaying only one level of the tree at a time - starting with the main code and its immediate child elements below it.

Is there a need to record and map the specific path taken to reach a certain point in the tree, thus allowing you to traverse back up from the top whenever necessary?

I hope this clarification helps avoid any confusion!

Answer №1

Let's make the following assumptions:

  • Each ID is distinct
  • You only require access to the parent node and not the entire path

There are two possible solutions. One option is to modify the JSON structure or create a duplicate, adding a _parent field for every node. Another approach is to maintain a map where the IDs serve as keys and the parent nodes serve as values.

In both scenarios, you can populate the additional data by recursively traversing the tree.

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

Creating multiple tabs in PHP using the header function can be achieved by specifying the location in

I am attempting to open a new tab using Php code: header("location:print_register.php?recpt_no=".$recpt_no); In addition, I would like to open two tabs programmatically with the following code snippet: header("location:print_register.php?recpt_no=".$rec ...

Retrieve JSON information from an API using Angular 2

I am facing an issue with retrieving JSON data from an API that I created. Despite using Angular code to fetch the data, it seems to be unsuccessful. Here is the code snippet: getBook(id: string){ return this._http.get(this.url + 'books/' + ...

Make sure the subset interface is selected from the interface / Choose PickDeep<>?

I am searching for a solution using the following interface: interface Person { age: number, name: string, hometown?: { city: string, zip: number } } type SubPerson = EnsureSubInterface<Person, { name: string }> an example that w ...

Mastering the art of mocking modules with both a constructor and a function using Jest

I'm a Jest newbie and I've hit a roadblock trying to mock a module that includes both a Class ("Client") and a function ("getCreds"). The Class Client has a method called Login. Here's the code snippet I want to test: import * as sm from &ap ...

Employing Jackson for serializing and deserializing an object containing nested JSON

I am working with an Entity class that has two String fields: name and description. The description field is meant to hold a raw JSON value like { "abc": 123 } @Getter @Setter public class Entity { private String name; @JsonRawValue private S ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

Turn off Chrome 69's autofill functionality

I've recently encountered an issue with Chrome's password autofill feature that has been troubling me for a few days now. This problem began when I was using Chrome version 69. After much trial and error, I found a solution by removing the id an ...

What is the best way to create a loop with JSON data?

My challenge is to showcase json data using a loop. I have received the following results, but I am unsure of how to display them with a loop. [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665"," ...

Implementing a try-catch-finally block in Javascript to handle errors during JSON parsing appears to be ineffective

As someone relatively new to web scripting, I find the similarities between Java try-catch blocks and Javascript ones intriguing. However, my attempts at using them have yielded slightly different results than expected. Here is a snippet of code showcasing ...

Is it possible to use the same identifier for both the name and id attributes in HTML?

In the world of coding, the "name" attribute is often used in server-side programming to send name/value pairs in requests. On the other hand, the "id" attribute is commonly utilized in client-side programming such as Javascript and CSS. However, both att ...

Modifying the color of the tooltip arrow in Bootstrap 4: A step-by-step guide

How can I change the arrow color of the tooltip using Bootstrap 4? Here is my current code: HTML: <div class="tooltip-main" data-toggle="tooltip" data-placement="top" data-original-title="Service fee helps Driveoo run the platform and provide dedicate ...

Control the start and stop of an Express.js app in Node.js using PHP

I'm currently developing a web service using express.js in the node.js npm environment. In order to deliver this project to my client, I need to create a controller file that allows me to start and stop the server without having to use the command pr ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

What kind of error should be expected in a Next.js API route handler?

Recently, I encountered an issue with my API route handler: import { NextRequest, NextResponse } from "next/server"; import dbConnect from "@/lib/dbConnect"; import User from "@/models/User"; interface ErrorMessage { mess ...

Typescript type/object's conditional property feature

Imagine having a recipe ingredient type structured like this export type RecipeIngredient = { name: string; amount: Number | string; unit: "grams" | "milliliters" | "custom"; }; To illustrate const apples: RecipeIngredient = { name: 'apples&a ...

Use Typescript to access and utilize the value stored in local storage by using the

Trying to retrieve the language setting from localHost and implement it in a translation pipe as shown below: transform(value: string): string {... localStorage.setItem("language", JSON.stringify("en")); let language = JSON.parse(loca ...

Send empty object using FormBuilder

When retrieving an object from a backend API service like this: data: {firstName:'pepe',lastName:'test', address = {street: 'Cervantes', city:'Villajoyosa'} } or data: {firstName:'pepe',lastName:'test ...

Utilize an exported class as a type within a .d.ts file

I have two classes, ./class1.ts and ./class2.ts, with the following structure: export class Class1{ ... } and export class Class2{ ... } In my file ./run.ts, there is a function that accepts a class input function doSomething(klass: ClassType){ l ...

Tips for preventing a Wistia video from playing in a tab when moving away from the tab

Hey everyone, I'm facing an issue with a jsp page that contains multiple tabs. One of the tabs has a wistia video embedded in it. In Firefox and Chrome, when I switch away from the video tab, the video stops playing as expected. However, in Internet ...

I'm encountering issues with this code for a dice game. It's strange that whenever I click the roll dice button, it disappears. Additionally, linking an .css sheet seems to cause the entire page to

I'm currently working with two separate codes: one for HTML and the other for JavaScript. I am facing an issue where the button keeps disappearing when I try to add any CSS styling to it. Even a basic CSS file seems to override everything else and lea ...