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

Guide for creating a CORS proxy server that can handle HTTPS requests with HTTP basic authentication

For my http requests, I've been utilizing a CORS-Proxy which works well for me. However, I recently stumbled upon an API for sending emails which requires http basic authentication for https requests. I'm uncertain of how to go about implementing ...

Inquiry regarding JSON manipulation and serialization techniques

I am facing an issue with passing a List of Skills along with a strongly typed view containing an object Person in my viewmodel. Working with the object Person using Html Helpers like @Html.TextBoxFor(m => m.Person.FirstName) is straightforward and I ca ...

Transferring cookies across subdomains

I am facing an issue with an ajax request going from one subdomain to another, for example from sub1.example.com to sub2.example.com. Despite having a cookie set for all domains (cookie domain='.example.com'), the cookie is not being sent to the ...

view multiple HTML documents simultaneously in a single browser tab

Currently, I am in the process of building a wiki and have included tables in various sections. I want to showcase these tables on the main page as well. Rather than constantly copying and pasting them, I'm looking for a way to have the main page auto ...

Transform boolean values to 1/0 instead of true/false in Jackson Serializing

I am working with a REST resource where I receive a JSON object that represents a map from user ID to a boolean value indicating if the user encountered errors. Due to the large number of users I expect to handle, I am looking to reduce the size of this J ...

Ordering an array based on two integer properties using JavaScript

Here is an array of objects I am working with: const items = [ { name: "Different Item", amount: 100, matches: 2 }, { name: "Different Item", amount: 100, matches: 2 }, { name: "An Item", amount: 100, matches: 1 }, { name: "Different Item" ...

Refresh text displayed on a button with the help of setInterval

I need help updating the text on a button with the id fixed-button at regular intervals. Here is the code I am currently using: <script type="text/javascript"> $(function() { $('#fixed-button').setInterval(function() { ...

Build a photo carousel similar to a YouTube channel

Is there a way to create an image slider similar to the one on YouTube channels? I've noticed that when there are multiple videos on a channel, YouTube displays them in a slider with back and forth buttons to navigate through the videos that aren&apos ...

When implementing the Dropdown Picker, it is important to avoid nesting VirtualizedLists inside plain ScrollViews for optimal

Currently, I am utilizing the RN library react-native-dropdown-picker. However, when I enclose this component within a ScrollView, it triggers a warning: "VirtualizedLists should never be nested inside plain ScrollViews with the same orientation because ...

How can I convert Double Quotes from (") to (&quot;) in TinyMce Editor?

While using TinyMce Editor, I have encountered a problem with double quotes breaking my code. In the HTML source of TinyMce, it displays " instead of &quot, causing issues in conversion. It seems that it is not converting " to " as it should, simi ...

Leveraging a nodejs script integrated with socket.io within an angular/electron hybrid application

I have successfully created an electron/angular app that is functioning well. Additionally, I have developed a nodejs script to open a socket.io server using typescript + webpack to generate all files in a bundled js file. My challenge arises when trying ...

Analyzing native-land.ca JSON data using R

I am a beginner when it comes to handling JSON files, and I'm a bit unsure about how to proceed. My goal is to create a plot using the json file for indigenous territories available from native-lands.ca. While I can read the file as JSON, I'm hav ...

Utilizing $.when to merge AJAX requests and then passing the resulting data to a designated function

I am struggling with sending data between functions and using $.when in my JavaScript code. I have separate functions and AJAX calls that update content on the page, but they need to load together on page load. Despite trying various solutions to combine A ...

Issue with rendering the search component due to a conflict with validate.js

I am currently facing an issue with my search component that includes validation using JavaScript. The problem I am encountering is that when I first focus on the input, the validation and request do not work. However, after losing focus on the input, cli ...

`Problem encountered when trying to present JSON content in an Android Gridview`

Encountering difficulties while attempting to showcase JSON data in a Gridview within an Android application using the Volley library through a URL. The error message received is: com.android.volley.NoConnectionError:java.io.IOException The JSON data i ...

I've successfully created the file in C#, but unfortunately, nothing seems to happen when trying to download

After successfully creating a file and uploading it, I am facing an issue with downloading the created file. Despite checking if the file exists and attempting to download it using the code below, nothing happens when the button is clicked. [HttpPost] ...

The issue of app.css and app.js resources not loading in Laravel 8 with nginx, resulting in a 404 not found error, needs to be

Although this question may appear to be a duplicate, I assure you it is different. I have thoroughly searched through Stack Overflow, Laracast, Reddit, and GitHub for a solution. My setup includes a Laravel application on an Ubuntu VM with Nginx. The pro ...

Tips for setting background colors as a prop for Material UI cards in React JS

Currently utilizing the Material UI next framework to construct a wrapper for the card component. This customized wrapper allows for personalization of the component. I have successfully extended the component so that the title and image within the card ca ...

Are the Bootstrap columns arranged in a vertical stack instead of side by side?

I currently have two large columns that are stacked vertically on top of one another. I want them to be side by side, like | 1 | 2 |, so that the user can view both columns simultaneously. I am seeking tips or suggestions on how to resolve this issue. Whil ...

What causes Next.JS to automatically strip out CSS during the production build process?

Encountering unpredictability in CSS loading while deploying my Next.JS site. Everything appears fine locally, but once deployed, the CSS rules seem to vanish entirely. The element has the attached class, yet the corresponding styling rules are nowhere to ...