A recursive function that utilizes a for loop is implemented

I am encountering a critical issue with a recursive function. Here is the code snippet of my recursive function:

iterateJson(data, jsonData, returnedSelf) {
  var obj = {
    "name": data.groupName,
    "size": 4350,
    "type": data.groupType
  };

  if (data.parentGroupName == jsonData.name) {
    jsonData.children.push(obj);
  } else {
    if (jsonData.children) {
      for (var i = 0; i < jsonData.children.length; i++) {
        if (data.parentGroupName == jsonData.children[i].name) {
          jsonData.children[i].children.push(obj);
          elementFound = true;
          break;
        }
      }
      if (elementFound) {
        return jsonData;
      } else {
        if (jsonData.children) {
          for (i = 0; i < jsonData.children.length; i++) {
            if (elementFound) {
              return jsonData;
            } else {
              jsonData = jsonData.children[i];
              jsonData = returnedSelf.iterateJson(data, jsonData, returnedSelf);
            }
          }
        }
      }
    }

  }

  return jsonData;

},

The issue I am facing is that in the second for loop, (jsonData.children.length)

The problem arises when my jsonData variable gets altered. How can I preserve the original parent jsonData?

I hope my question is clear. I will provide further clarification to make it more concise. Let's say initially jsonData contains 5 elements, and I enter the loop, take the first child as the new jsonData, and call this function again. When the condition is met, instead of returning to the loop with the original 5-element jsonData, it has the new json data which is the first child element of the original jsonData.

My query is how can I maintain the parent jsonData with 5 elements.

Answer №1

While I may not have specific details about the input data:

jsonData = jsonData.children[i];
jsonData = returnedSelf.iterateJson(data, jsonData, returnedSelf);

These lines of code are crucial for updating jsonData.

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

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...

Revamp the appearance of angular material inputs

I have been working on customizing the style of an Angular Material input. So far, I successfully altered the background-color with the following code: md-input-container { padding-bottom: 5px; background-color: #222; } I also changed the placeh ...

Minimization tools for compressing CSS and JavaScript documents

After deploying my application, I noticed that the loading time has significantly increased. Is there a way to compress CSS and JS files? I include only the necessary code in each page and occasionally use minified versions of JS. Thank you. ...

Struggling to identify the cause of the null pointer exception error

Lately, I've been working on developing an Android app and everything was running smoothly up until now. Suddenly, I encountered a null pointer error that has me stumped. The strange thing is that the app was functioning perfectly before this error po ...

Changing the text color of Material UI Accordion Summary upon expansion

How can I update the color of an Accordion summary text in Material UI when it is expanded? <Accordion expanded={expanded === 'panel1'} onChange={handleChange('panel1')} className={classes.root}> <AccordionSummary ...

What is the best way to handle texture loading delays in Three.js when using a JSON model?

Currently, I have successfully loaded a JSON model based on AlteredQualia's skinning example. However, I am looking to hide the model until it is fully loaded. In the provided example, the models are displayed before their texture resources finish loa ...

The type 'Event' argument cannot be assigned to the 'InfiniteScrollCustomEvent' parameter

I'm facing an issue with Ionic Angular. Here is my movies.page.html: <ion-header> <ion-toolbar color="primary"> <ion-title>Trending Movies</ion-title> </ion-toolbar> </ion-header> <ion-content ...

What is the best approach to accessing a key within a deeply nested array in JavaScript that recursion cannot reach?

After hours of research, I have come across a perplexing issue that seems to have a simple solution. However, despite searching through various forums for help, I have reached an impasse. During my visit to an online React website, I stumbled upon the web ...

What is the process for sending values to a component?

I am working with a component called MyComponent: export class MyComponent { @Input() active:boolean; constructor() { console.log(this.active); } } In this component, I have declared an Input, and I pass it in as follows: <mycomp ...

Ways to leverage the power of Reactivity APIs in Vue.js

In my Vue application, I am trying to create a Drop Down Menu by using a variable called "showDropDown". The idea is to use a v-if directive to check if the value of showDropDown is true, and then display the menu accordingly. Additionally, I want to imp ...

What aspects of MongoDB security am I overlooking?

Is it a secure way to connect to Mongo DB by using Node JS, Mongo DB, and Express? Could someone provide an explanation of this code in terms of security? === Many tutorials often only show... var mongoClient = new MongoClient(new Server('localhos ...

What is the method for passing an element object instead of an id in JSXGraph?

I'm attempting to modify var brd2 = JXG.JSXGraph.initBoard('box', {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); to read as var brd2 = JXG.JSXGraph.initBoard(this.$('#box'), {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); Due to the creat ...

When making an API request, the response includes the body of the data, however, the specific properties cannot be

I've encountered an unusual bug while using the Mapbox geocoding API. const geocode = async (address, callback) => { const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=token&limit=1` try { ...

Utilizing the `useNavigate` function from react-router v6 within a class component to navigate and manage

I have a situation where I need to redirect a class component to another page. To achieve this, I came up with a function that decorates the export of the class component in order to navigate within the component's state. import { useNavigate } from & ...

Animating object properties instead of static values

I am faced with a challenge of dealing with a large array of objects, all having the same structure: { title: 'Text', value: 'Text'} My goal is to loop through this array using a map function and display only two objects at a time. Th ...

What is the best way to utilize RxJs with jQuery's ajax function?

Here is how I've set it up: Rx.Observable.fromPromise($.ajax({ url: url + postal_value + '&types=(regions)&location=51.509865,-0.118092&key=' + key, type: "GET", datatype: "json" })); However, the aj ...

Tips for displaying JSON data by formatting it into separate div elements for the result object

Having recently started using the Amadeus REST API, I've been making AJAX calls to retrieve data. However, I'm facing a challenge when it comes to representing this data in a specific format and looping through it effectively. function showdataf ...

Building a Nested JSON Object with Google Apps Script

I am looking to structure a JSON object with the following details: var log_data = { total_successful: 0, total_failed: 0, [log_entry: { time: "1a", action: "New Task", type: "Automation", ...

Incorporating script within an ASPX webpage

I've been struggling with using this code on an ASPX page. I keep trying to implement it within a text box on the same page, but without success. Strangely though, I can successfully use the script within a text box in my master page. Any assistance w ...

Having trouble with downloading a node module?

I encountered an issue while trying to download the node-sass node module. The error message I received was as follows: To download the node-sass module, use the command: npm install --save-dev node-sass Error Binary has a problem: Error: \?\C: ...