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

AngularJS allows for the creation of cascading dropdown selects, where the options in the second select

I'm struggling to access the version data stored in the server model, but it's not cooperating. My suspicion is that when the page loads, the initial data from the first select isn't available yet because it hasn't technically been sel ...

Upon attempting to add a new component, an error was encountered: Uncaught SyntaxError: Unexpected token export

I have created a React test project and added modules to my package.json as follows: { "name": "untitled", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-node5": "^12.0.1", "react-scripts": "0.9.5" }, "depe ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

Issues with React router arise once the app has been built

I am new to utilizing react and react-router in my project. I have built the application using create-react-app and now I am facing an issue with routing between two main pages. After trying different approaches, I managed to get it working during develop ...

Encountered an issue while loading a pretrained JSON model in a JavaScript script within a locally hosted

At the moment, I am using TensorFlow in Python to train a model and saving it as model.json along with the BIN file in a folder named models. My goal is to develop a web application that can load this pre-trained model for prediction. However, I have been ...

Deciding on excluding empty key:value pairs from an object for various filtering needs

One of the features in my app allows users to filter results by "blood group" and "city", along with other areas. The information is retrieved from a database using Axios for Vuejs, incorporating query strings within the URL. For example: http://example.co ...

Fetching Data from JSON Object Using PHP

My goal is to extract specific objects from the data stored in a .json file. I am particularly interested in accessing the individual items within the stylers object. However, I am encountering difficulties in retrieving information related to color or vis ...

Adding a new key/value pair to a nested object in Aerospike

Is there a way to add a new key/value pair in a nested object stored in bins of type map in Aerospike? For example, let's say I have the following key/value pairs stored in bins of type map: { "a" : "apple", "b" : "ball", "c" : { "d" : "dog", ...

Is it possible to continuously generate webpages using AJAX?

Is there a way to achieve an infinite scrolling effect in all directions using ajax requests without the need for flash or silverlight? If anyone has an example of this, I would love to see it! Thank you for your time. ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

Utilizing property validation in your codebase

How can I set up my code to display a warning in the console if the value of the Prop is not a string? The player-name prop should always be a string. If this: <greet :player-name="5"></greet> contains a number, I want my code below to generat ...

Displaying client-side filtered rows in a jqGrid with postData filter upon initial loading

Our website includes a jqGrid that initially retrieves its rows using the built-in ajax fetch feature, returning a json object. We then apply filtering and searching on the client side by creating custom functions to generate postData filters. However, we ...

Exploring jQuery Mobile | Moving Seamlessly between Pages

I'm relatively new to JQM and I'm working on creating a mobile application using jQuery Mobile. Here's the goal I'm aiming for: I have multiple HTML pages, each with its own CSS, JavaScript, and JQM components. What I want is to be ab ...

The error message "element is not defined" is indicating an issue related to the cordova-plugin-google

In my current project using Ionic 3, I decided to implement map-related features by incorporating the Google Maps plugin recommended by the Ionic Team. This specific plugin serves as a wrapper around cordova-plugin-googlemaps. Following the steps outlined ...

error in jquery when splitting

I encountered an issue while trying to split data for checkboxes. var ukuran = data['model'].ukuran_model; var cek = ukuran.split(",").join('], [value='), $inputs = $('input[name^=ukuran]'); $inputs.filter('[value=&a ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

Utilizing JavaScript: Storing the output of functions in variables

Currently in the process of learning JavaScript and aiming to grasp this concept. Analyzed the following code snippet: function multiNum(x, y){ return x * y; } var num = multiNum(3, 4); document.write(num); Decided to try it out on my own, here's ...

How to implement a form in PHP that doesn't refresh the page upon submission

I am having an issue with this ajax code. I know it works, but for some reason it's not submitting. <script type="text/javascript"> $(function(){ $('input[type=submit]').click(function(){ $.ajax({ type: "POST", ...

Krajee Bootstrap File Input, receiving AJAX success notification

I am currently utilizing the Krajee Bootstrap File Input plugin to facilitate an upload through an AJAX call. For more information on the AJAX section of the Krajee plugin, please visit: Krajee plugin AJAX The JavaScript and PHP (CodeIgniter) code snippe ...

With the use of discreet JavaScript, the parameter is not empty; instead, it contains values

Previously, my JavaScript code was functioning correctly when it was within the same page as my cshtml file: function SaveEntity() { // more code here alert(entity.FirstName); /* this shows that entity's properties have values */ $.post( ...