Utilize recursive and for loop methods for parsing JSON efficiently

I have a JSON file that requires parsing. I'm attempting to implement a recursive method for this task. The current JSON data is structured as shown below:

Item 01
 SubItem 01
  InnerSubItem 01

Item 02
 SubItem 01
  InnerSubItem 01

Unfortunately, the function I wrote only manages to parse the first set of data (The contents under Item 01). It seems like the code does not loop back when the condition is false.

Here is the code snippet I used:

$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
  repeat(data, data.layers);
})

function repeat(data, x) {
  var layer = data.layers.reverse()
  for (i = 0; i < x.length; i++) {
    name = x[i].name
    console.log(name)
    if (x[i].layers.length > 0) {
      repeat(data, x[i].layers)
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №1

You may encounter issues with your code if the object does not have a layers property. It is important to first check for its existence before proceeding to check for length.

For example:

if (x[i].layers && x[i].layers.length > 0)

Here is the revised code:

$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
  repeat(data, data.layers);
})

function repeat(data, x) {
  var layer = data.layers.reverse();
  for (var i = 0; i < x.length; i++) {
    name = x[i].name;
    console.log(name);
    if (x[i].layers && x[i].layers.length > 0) {
      repeat(data, x[i].layers);
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Additionally, it appears that you are not using the reversed array and are passing data unnecessarily each time repeat is called. Consider simplifying the code as follows (reverse the array if needed):

$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
  repeat(data);
})

function repeat(data) {
  if (!data || !data.layers)
    return;

  var x = data.layers;
  for (var i = 0; i < x.length; i++) {
    name = x[i].name;
    console.log(name);
    repeat(x[i]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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 map with multiple markers by utilizing JSON, PHP, and Google Maps API Version 2

I am currently working with Google Maps API V2 (I know, it's outdated but I have to stick with V2 because I am modifying existing code). All the markers on the map are pointing to the correct locations, but there's one infuriating issue that is d ...

Unable to access the inner object using key-value pair in Angular when working with Firebase

Within my json object, there is an inner object labeled data, containing {count: 9, message: "9 sites synced"} as its contents - also in json format. My objective is to extract the value from message, rather than count. Provided below is the temp ...

If an interface property is set as (), what significance does it hold?

While exploring the Vue.js source code located at packages/reactivity/src/effects.ts, I came across this snippet: export interface ReactiveEffectRunner<T = any> { (): T effect: ReactiveEffect } I'm curious, what does () signify in the code ...

Unable to establish connection between Router.post and AJAX

I am currently in the process of developing an application to convert temperatures. I have implemented a POST call in my temp.js class, which should trigger my ajax.js class to handle the data and perform calculations needed to generate the desired output. ...

What steps can be taken to avoid the appearance of the JavaScript prompt "Leaving site"?

Hi there, I'm currently trying to find a way to remove the Javascript prompt/confirm message that asks "Do you want to leave this site?" like shown in this link: The issue I am facing is that when a modal opens and the user clicks on "YES", it redire ...

Display a div element for a specified amount of time every certain number of minutes

I am currently utilizing AngularJS, so whether the solution involves AngularJS or pure JS does not make a difference. In the case of using AngularJS, I have a parameter named isShowDiv which will determine the switching between two divs based on the follow ...

Use ajax to add rows to the second-to-last table

I am facing a situation where I have a table with 25 default rows. When scrolling to the bottom of the table, I want to dynamically insert another set of 25 rows. Everything is functioning correctly, but in a specific scenario, I need to preserve the last ...

Reactstrap: Is it necessary to enclose adjacent JSX elements within a wrapping tag?

While working on my React course project, I encountered an issue with my faux shopping website. The error message that keeps popping up is: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...& ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

Creating an Interactive and Engaging 3D Experience on Facebook with the Power of Javascript API

Looking for suggestions on a 3D API in JavaScript that can be used to create immersive applications on Facebook. Is there something similar to this one: ? Appreciate any insights. ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Ensure to close the Ajax request from PHP before the script finishes executing

Is there a way to terminate an Ajax request from PHP before the script finishes executing? For instance, if a user requests php.php and it includes the line 'echo "phpphp"', how can we ensure that the Ajax request is completed with the data "phpp ...

Jump straight to the top of the page with just a click using the Google Maps Store Locator

When I use my Store Locator and click on an anchor like "Zoom Here," "Directions," or "Street View," the href hash always brings me back to the top of the page. How can I prevent this from happening? I've tried examining the minified source code for t ...

What is the best way to perform a callback after a redirect in expressjs?

After using res.redirect('/pageOne') to redirect to a different page, I want to call a function. However, when I tried calling the function immediately after the redirect like this: res.redirect('/pageOne'); callBack(); I noticed th ...

Tips for initiating a jQuery form submission

At this moment, the form is being submitted using the default URL. I would like it to utilize the form submit event in my JavaScript code so that it can pass the .ajaxSubmit() options. Below is the corresponding JavaScript code: $('#selectedFile&a ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Exploring search capabilities within D3 graph nodes

After creating a JSON file with four tiers and utilizing D3.js's collapsing box format to visualize it (source: https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460), I've run into an issue. The problem stems from the sheer size of the J ...

showing images received via a websocket connection

My current setup involves receiving one image per second through a WebSocket connection. The images are in blob format, and I am unsure of the best way to display them. Should I use an image tag or a video player? And how should I go about showing these ...

How to Extract Minutes in Datatables Timestamps and Apply Custom Styling

Working with Datatables v1.10 Right now, my table is showing a date in the second column in the format 17-04-2019 14:34, which is how it's stored in the database. The filtering and searching functionality are all working as expected. The current HTM ...