Exceeded call stack size due to iterating through nested JSON structures

I'm currently working on a recursive function to navigate through a nested JSON structure. However, I've run into an error that says:

Maximum call stack exceeded

The function I've written looks like this:

function createTreeMap (treeCatalog){
  var _this = this;

  _.each(treeCatalog, function (ele, inx){
    if(typeof (ele) === "object"){
      createTreeMap(ele);
    }else{
      //Here I create another JSON structure with the value as its property and set it to 1.
      _this.treeMap[ele] = 1;

    }
  });

}

The JSON data I'm traversing through is structured as follows:

[{
    "EmployeeID": 2,
    "FirstName": "Andrew",
    //... employee details here
    children: [{
        "EmployeeID": 8,
        "FirstName": "Laura",
        //... more employee details
    }, {
        //... additional employees
    }]
}];

I suspect that the issue may be related to similar child property names. Is there a proper way to address this while keeping the requirement for similar child names?

Thank you for your assistance :)

UPDATE

Check out this example that demonstrates the issue I'm facing: http://jsfiddle.net/qaoapays/1/

Answer №1

Upon attaching your source to jqxTreeGrid, a minor modification is required in its structure: include the parent property and the data property, where data is a reference to itself.
As a workaround to prevent infinite recursion, you need to exclude this property, like so:

function iterate (obj){
    _.each(obj, function(ele, inx){
        if(typeof (ele) === "object" && ele !== obj && inx !== 'parent'){
            iterate(ele);
        }else{
            console.log(ele);
        }
    });
}

 // Sample employee data
var employees = 
      [{
      "EmployeeID": 2,
          "FirstName": "Andrew",
          "LastName": "Fuller",
          "Country": "USA",
          "Title": "Vice President, Sales",
          "HireDate": "1992-08-14 00:00:00",
          "BirthDate": "1952-02-19 00:00:00",
          "City": "Tacoma",
          "Address": "908 W. Capital Way",
     children: [{
          "EmployeeID": 8,
              "FirstName": "Laura",
              "LastName": "Callahan",
              "Country": "USA",
              "Title": "Inside Sales Coordinator",
              "HireDate": "1994-03-05 00:00:00",
              "BirthDate": "1958-01-09 00:00:00",
              "City": "Seattle",
              "Address": "4726 - 11th Ave. N.E."
      }, 
      // Add more employees here
      }],
  }];

  //// prepare the data
  // Data source setup
  var source = {
      dataType: "json",
      dataFields: [{

          // Define data fields
      }],
      hierarchy: {
          root: 'children'
      },
      id: 'EmployeeID',
      localData: employees
  };
  var dataAdapter = new $.jqx.dataAdapter(source);

  // create Tree Grid
  $("#treeGrid").jqxTreeGrid({
      // Configure Tree Grid
  });
  $("#jqxbutton").jqxButton({
      // Setup button
  });
  $('#jqxbutton').click(function () {
      // Button click action
      $("#treeGrid").jqxTreeGrid('expandRow',2);
      iterate(employees);
      });

  function iterate (obj){
    // Recursive function
  }
<script src=" inserted script resources here "></script>
    // Include necessary scripts and styles
<div id="treeGrid"></div>
<input type="button" style="margin: 20px;" id="jqxbutton" value="Expand a row" />

Alternatively, you can resolve this issue by passing a deep-cloned object to the data source.

Answer №2

It appears that you may be mistakenly placing the object you are labeling as "ele" back into the function itself, Hasitha.

Instead of:

createTreeMap(ele);

Consider trying:

createTreeMap(ele.child);

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

Ways to verify the presence of an item in a MonoDB array

My MongoDB model looks like this: const userSchema = new Schema = ({ name: { type: String }, company: [ companyId: { type: String, }, movies: [ { genre: { type: String, enum: [ ...

Submitting a specific form when a change occurs in CodeIgniter

I am currently developing a POS web application. My current task involves creating a form for each item in the cart/order, meaning multiple forms generated in a loop with unique IDs (e.g. 'id'=>'cart_'.$line )(cart_1, cart_2). I hav ...

How can I include line breaks using HTML `<br>` tags in a textarea field that is filled with data from a MySQL

Within a modal, I am showcasing a log inside a read-only <textarea> field that contains data fetched from my MySQL database. Below this, there is a writable <textarea> field where users can input updates to the log, which are then added to the ...

What is the reason that when we assign `'initial'` as the value for `display` property, it does not function as intended for list elements?

To toggle the visibility of elements, I have created a unique function that accepts an object and a boolean. Depending on the boolean value, either 'none' or 'initial' is assigned to the 'display' property of the specified obj ...

Using JavaScript arrays to populate an HTML form

I am new to JavaScript, although I have some experience with Python, and I find it challenging to integrate JS with HTML. I am attempting to convert an array into an HTML dropdown list, but I am struggling to make it function correctly. <HEAD> ...

Unable to render page with scrapy and javascript using splash

I am currently trying to crawl this specific page. Following a guide on Stack Overflow to complete this task, I attempted to render the webpage but faced issues. How can I resolve this problem? This is the command I used: scrapy shell 'http://local ...

What causes z-index to be ineffective with sticky elements?

In my website, I've implemented rollover effects in a sticky footer and a responsive menu that stays at the top. However, when the menu is opened and extends over the footer, it covers everything except the rollovers. Closed navigation http://www.mus ...

Extract data from a JSON file containing only the root element on an Android device

I'm looking to extract JSON data from The Movie Database in a specific structure: [ { "iso_3166_1": "AD", "english_name": "Andorra" }, { "iso_3166_1": "AE", "english_name": "United Arab Emirates" }, This is the API servic ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Is it possible to share a Vue.js component by "transferring" it rather than duplicating it?

In my comment system project using Vue.js, I have over 300 comments to manage. Each comment has an admin section that appears when the cursor hovers over it. Duplicating the admin section component for each comment is not ideal as it creates unnecessary l ...

What could be causing the string arrays in my array to unexpectedly become null values?

I am currently working on a project that involves retrieving JSON data from an API and displaying it in a user interface. However, I have encountered an issue where the JSON data turns into null when I parse it and put it into an array using a for loop. I ...

What is the maximum number of JavaScript functions allowed in a single HTML file?

My HTML5 file includes JavaScript (created from CoffeeScript) directly within the HTML file, as I prefer this approach for my HTML/JavaScript programming. The code consists of four JavaScript functions that convert one temperature unit to another. Strang ...

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

I am seeking assistance in troubleshooting this javascript code. Can someone please help me identify the issue?

function validateCredentials() { var username = document.forms["myForm"]["name"].value; var admin = "admin"; var user = "user"; var master = "master"; if (username == "&qu ...

The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that t ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Ways to retrieve the state from the Redux store

While working on setting up the Redux store in my app.js file, I found myself populating it with data from the database. However, now I am faced with the task of obtaining the state of the store in a plain JavaScript file, not a React class. If I was work ...

Dynamic JSX tag including attributes

In my project, I have a set of components stored in a folder named systemStatus. These components are accessible through an index.js file as follows: export UserCount from './UserCount' Additionally, I have a JSX component called Status which i ...