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

Creating a simulated provider class to simulate a response and manage promises - Implementing Unit Testing using Jasmine and Karma within an Ionic 3 environment

I am relatively new to Unit Testing and have recently started writing tests for my Ionic 3 Application using Karma and Jasmine. I referred to blogs to configure everything correctly and successfully tested the initialization of App component. Additionally, ...

JavaScript inquiry

How do you typically utilize JavaScript in your projects? I often use it for form validation, creating dropdown menus, and more. Do you have any unique ways of using JavaScript? Personally, I find jQuery to be a superior tool in certain situations... ...

Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful. Here is ...

Discovering the method for accessing a variable within jQuery from a regular JavaScript function

As someone new to jQuery, I am currently facing a challenge with accessing a variable defined inside a jQuery block from a regular function. Despite my attempts, I have been unsuccessful in accessing it. Can anyone guide me on how to do this? <script l ...

Converting retrieved data into table cells through mapping

I'm facing an issue where I need to display specific addresses for each individual in a table row. For simplicity, let's focus on showing the city specifically as described in this code snippet: https://i.stack.imgur.com/bJmsD.png Currently, whe ...

Obtaining a URL in JavaScript

Hey there, I'm diving into the world of JavaScript and could use some guidance. I'm currently working on implementing forward and backward buttons on a webpage. The URL structure is http://webaddress.com/details?id=27 My goal is to write two fun ...

Using JQuery to implement a date and time picker requires setting the default time based on the server's PHP settings

I have implemented a jQuery UI datetime picker in my project. As JavaScript runs on the client side, it collects date and time information from the user's machine. Below is the code snippet I am currently using: <script> // Function to set ...

Angular is having trouble with binding

What seems to be the issue in this code snippet? JSFiddle. function SecondCtrl($scope, Data) { $scope.data = Data; $scope.reversedMessage = function(message) { return message.split("").reverse().join(""); }; } ...

`The validation in Angular 12 is successful, yet the mat-input remains invalid.`

Code snippet of Component- ngOnInit(): void { this.form = this.fb.group({ currentPassword: ['', [Validators.required], [this.matchCurrentPassword]], newPassword: ['', [Validators.required, Validators.minL ...

Obtain the AJAX response in separate div elements depending on whether it is successful or an error

Currently, my jQuery script outputs the result in the same div for error or success messages: HTML <div id="error-message").html(res); JQUERY jQuery('#register-me').on('click',function(){ $("#myform").hide(); jQuery ...

Creating adaptable HTML images by specifying width and height attributes within the image tag

My current website setup involves loading a full image and automatically adjusting its size to fit the screen by setting the image width to 100% in CSS. While this method works smoothly, it may not be following standards as I am not specifying width and he ...

I am experiencing issues with the Link component in Next.js version 13.4, as it

Whenever I attempt to navigate by clicking on the buttons labeled About, Experience, and others, the page does not redirect me accordingly. Oddly enough, if I manually input the endpoint for that specific page like http://localhost:3000/#about, it function ...

Invoking a function within the directive's controller

How can I access and call the method defined within the directive controller externally? <div ng-controller="MyCtrl"> <map></map> <button ng-click="updateMap()">call updateMap()</button> </div> app.directive(&a ...

Attempting to configure a discord bot. Can anyone help me identify the issue?

I've been working on setting up a discord bot using Discord.js. I have all the necessary tools installed - Node.js, Discord.js, and Visual Studio Code. I've even created an application and obtained a token for my bot. However, I'm running in ...

What causes the off-canvas menu to displace my fixed div when it is opened?

Using the Pushy off-canvas menu from GitHub for my website has been great, but it's causing some trouble with my fixed header. When I scroll down the page, the header sticks perfectly to the top, but once I open the off-canvas menu, the header disappe ...

How can I export an ES Object in Node.JS to an NPM package?

I am currently facing a challenge involving an ES5 object/function that I want to integrate into an NPM package. This particular object is within a namespace defined as MY_NAMESPACE.myObject = function(){...} where MY_NAMESPACE is simply an object. Typic ...

express-typescript-react: The frontend bundle file could not be located (404 error)

Currently, I am in the process of developing a full stack application that utilizes Express (written in Typescript) and React. One key component of my development setup is webpack, which I'm using to bundle both the backend and frontend parts of the a ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...

The error message "TypeError: defineCall is not a function. require() fails" indicates that

Upon joining a new project, I encountered an issue with the database model built using Sequelize. It seems that I am unable to import more than a few files using sequelize.import before running into a TypeError: defineCall is not a function. The problem ap ...

Struggling with uploading files in AngularJS?

Below is the code snippet from my controller file where I aim to retrieve the values of various input elements (name, price, date, image) and store them in an array of objects... $scope.addBook = function(name, price, date, image) { name = $scope ...