Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure.

I need a way to navigate between these objects by following the array and then back again. What would be the most efficient approach to achieve this in TypeScript?

I attempted using forEach, but encountered difficulties navigating back. Nested for loops are not viable either due to varying levels of arrays present. I thought about using an iterator, but my knowledge of Angular/TypeScript is limited.

Below is a snippet of the data. It represents a questionnaire where each question needs to be displayed individually.

"questionId": 1,
"parent": null,
"description": "Question 1?",
"children": 
[
    {
        "questionId": 2,
        "parent": 1,
        "description": "Question 2?",
        "children": 
        [
            {
                "questionId": 4,
                "parent": 2,
                "description": "Question 4?",
                "children": []
            }
        ]

    },
    {
        "questionId": 3,
        "parent": 1,
        "description": "Question 3?",
        "children": []
    }
]

Apologies if my explanation is unclear or incomplete. This platform is new to me.

Answer №1

If you are looking to loop through all the question items efficiently, one approach is to flatten the data structure using a recursive function as shown below,

const transformQuestions = (questionData) => {
  const transformedQuestions = []
  transformedQuestions.push({id: questionData.id, parent: questionData.parent, text: questionData.text})
  for (let i = 0; i < questionData.children.length; i++) {
    const childQuestion = questionData.children[i];
    transformedQuestions.push(...transformQuestions(childQuestion))
  }
  return transformedQuestions
}

This transformation will result in an output similar to this:

[
  {
    id: 1,
    parent: null,
    text: "What is question 1?"
  },
  {
    id: 2,
    parent: 1,
    text: "What is question 2?"
  },
  {
    id: 4,
    parent: 2,
    text: "What is question 4?"
  },
  {
    id: 3,
    parent: 1,
    text: "What is question 3?"
  }
]

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

Is Angular 10 disregarding set-cookie response headers?

After logging in, I attempted to utilize a session auth cookie without success. To troubleshoot, I implemented a basic "CookieTest" method on my Dotnet Core server: [Route("CookieTest")] public ActionResult CookieTest() { var options = new CookieOptions ...

Unable to transmit information back to React

Recently stepping into the world of React and Node.js, I have successfully created a function in my Node.js application that executes a Python script using child process. However, I seem to be facing a challenge with my router post method named pythonExecu ...

Creating a Scrollable React Form Group

Struggling to display a large amount of data that is not scrollable, how can I make this form group scrollable to easily view all the data? render() { return ( <div style={{width: '50rem', margin: '1rem&ap ...

Is it possible to conceal and completely empty the TextBox once the checkbox is deselected?

When the checkbox is checked, the textbox is displayed; otherwise, it remains hidden. However, the value is not being cleared. Can someone please help me with this issue? Thank you in advance. HTML <div class="munna"> <in ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

Updating the status of various sections with Redux toolkit

Is it possible to update the state of a store, which consists of multiple slices, with a new state in React using Redux Toolkit? While you can revert the entire store to its initial state using extraReducers, is it also possible to change the state to som ...

I am interested in utilizing angular 4 ng2-ui/map with places-auto-complete functionality that is restricted to a specific country

Check out my code snippet below: <input class="form-control" placeholder="Pickup Location" places-auto-complete (place_changed)="pickupChanged($event)" formControlName="pickup_location" [types]="['geocode']" /> I am trying to figure out ...

What's stopping me from using useState() to assign API data to an array?

I have a question regarding my app that makes use of the Movies API. I am making an API request and then passing the data to an array using the useState hook. Here is a snippet of my code: const App = () => { type MovieType = { rate: string, ...

Inform the PHP backend that the browser has been closed by the frontend Angular application

Currently, I am working on an Angular project that is interacting with a backend project created using PHP and ZF3. I am trying to figure out the most efficient method of informing the backend project when the user closes the browser window. Initially, I ...

What is the standard text displayed in a textarea using jQuery by default

My goal is to display default text in a textarea upon page load. When the user clicks on the textarea, I want the default text to disappear. If the user clicks into the textarea without typing anything and then clicks out of it, I'd like the default t ...

Analyzing Compatibility and Ensuring Security

I recently started using Parse and have been exploring the documentation and answered questions. However, I still have a couple of inquiries on my mind. Firstly, I discovered that the Javascript SDK does not function on IE9 and IE8 without an SSL certific ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

What is the best way to create a visual separation between these two arrows using styled-components?

Currently, I am immersing myself in styled-components and attempting to replicate the image provided below. Although I can achieve this with CSS, I am solely focusing on utilizing styled components for this task. <Container> {sliderItems.map((item) ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

Combine two sets of 2D arrays by merging the rows that have matching values in a specific column

I am looking for a way to merge two arrays without removing any elements from either array. Array1 will always include date and price1 elements, while array2 will always have date and price2 elements. If both arrays contain the same date (e.g., 1-Sep-2016) ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

Static addition of the Button to the parent div is crucial for seamless

Introduction: My current project involves managing interns, and I am focusing on the employee side. Employees have the ability to add, edit, and delete interns through modal popups. Strategy: To avoid unnecessary repetition of code, I decided to create a ...

The onCall function in Firebase's realtime database does not provide a response data object when executing the remove() operation

When using onCall to perform a remove operation from a realtime database, I encountered an issue where the response only returned null instead of the expected data object. Strangely, I have used onCall for other operations like update and always received a ...

Sidenav Angular Material cdkScrollable is an effective tool for creating scrollable

In Angular Material CDK, there is a special Directive called CdkScrollable that allows you to monitor ScrollEvents within a specific container. I am currently attempting to retrieve the CdkScrollable associated with the default MatSidenavContent. Unfor ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...