In Javascript, ensuring a stopping condition for a recursive function that is looping through JSON data

I am having trouble figuring out how to set the break condition for this recursive function. Currently, the function is causing the browser to freeze (seems to be stuck in an endless loop).

My goal is to create a series of nested unordered lists based on the data provided in the list object.

You can view the fiddle here: https://jsfiddle.net/mzckoc7s/

var list = {
    "primary": [{
        "item": "item 1"
    }, {
        "item": "item 2",
        "secondary": [{
            "item": "item secondary 1"
        }, {
            "item": "item secondary 2"
        }, {
            "item": "item secondary 3",
            "secondary": [{
                "item": "item inner secondary 1"
            }]
        }]
    }, {
        "item": "item 3"
    }]
}

function items( obj ) {
    var output = '<ul>';
    for ( i = 0; i < obj.length; i++ ) {
        output += '<li>' + obj[i].item + '</li>';
        if (typeof obj[i].secondary != 'undefined') {
            items( obj[i].secondary );
            break;
        }
    }
    output += '</ul>';
    return output;
}

The expected result should look like this:

<ul>
<li>item 1</li>
    <li>item 2
        <ul>
            <li>item secondary 1</li>
            <li>item secondary 2</li>
            <li>item secondary 3
                <ul>
                    <li>item inner secondary 1</li>
                </ul>
            </li>
        </ul>
        </li>
    <li>item 3</li>
</ul>

Answer №1

One possible method is to use a nested approach by iterating through the keys of the object and the potential arrays. This way, you can construct the output while also handling cases where children are not provided.

function generateList(object) {
    var output = '';
    object && typeof object === 'object' && Object.keys(object).forEach(function (k) {
        if (k === 'item' || !object[k]) {
            return;
        }
        output = output || '<ul>';
        output += (Array.isArray(object[k]) ? object[k] : [object[k]]).map(function (a) {
            return '<li>' + a.item + generateList(a) + '</li>';
        }).join('');
    });
    output += output && '</ul>';
    return output;
}

var myList = { primary: [{ item: "item 1" }, { item: "item 2", secondary: [{ item: "item secondary 1" }, { item: "item secondary 2" }, { item: "item secondary 3", secondary: { item: "item inner secondary 1" } }] }, { item: "item 3" }] },
    finalResult = generateList(myList); 

document.body.innerHTML = finalResult;
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

The ng-repeat for nested JSON is failing to iterate properly

I'm having trouble retrieving the value 1 as shown below: var obj = { {"name":"name"}, {"contents":[{'one':1,'two':2}]} }; function MyController($scope) { $scope.items = obj; $scope.contents = obj.contents; } {{c ...

Flatten a multidimensional array in PHP while preserving keys

I have written some PHP code to organize the children of an array using a recursive function. While everything is displayed correctly in one column, some arrays are missing the "Name" key. Does anyone know how I can ensure that all elements display their ...

Methods for determining the disparity in days between two dates and the ratio of days yet to come

Within my React project, I am in need of a functionality that calculates the number of days remaining between two specific dates. Essentially, I want to determine how many days are left from today until the expiration date, and then calculate the percentag ...

The submit button fails to function properly in the presence of multiple fields

Encountering an issue where the Submit button becomes unresponsive when multiple addresses are generated. To resolve this, I attempted to use JavaScript. @foreach ($userDetails as $addr) <div class="order_container"> <input type="hid ...

What is the method to design a file upload feature without a specific form using JavaScript?

I am currently working on a form that handles file uploads using jQuery and AJAX. The goal is to upload the files individually as JSON containing base64 data. Rather than uploading all the images at once, I want each image to be treated as if it were in it ...

javascript create smooth transitions when navigating between different pages

As a newcomer to JS, I am currently working on creating a website with an introduction animation. My goal is to have this animation displayed on a separate page and once it reaches the end, automatically redirect to the next webpage. <body onload="setT ...

Immersive pop-up interface displaying a variety of embedded videos simultaneously

I am a beginner in JavaScript and I came across a CodePen that does exactly what I need, but it currently only works for one embedded video. What I aim to achieve is similar functionality, but with 6 videos. (function ($) { 'use strict'; ...

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

Tips for maintaining the particles.js interaction while ensuring it stays under other elements

I have incorporated particle.js as a background element. By adjusting the z-index, I successfully positioned it in the background. While exploring solutions on the Github issues page, I came across a suggestion involving the z-index and this code snippet: ...

Utilizing React Router with Material-Table for Efficient Column Value Filtering

Is there a way to dynamically pass Route params into the filtering fields of a React table component? I am currently utilizing the material-table component and have a list of links structured like this: <ul> <li> <Link to="/Products/ ...

Vue 3's "<Component :is="">" feature magically transforms camelCase into lowercase

Within my application, I have implemented a feature where users can customize the appearance of social media links on their page by defining which platforms they want to include. Each social media platform is represented by its own component responsible fo ...

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 ...

Determine how to use both the "if" and "else if" statements in

/html code/ There are 4 textboxes on this page for entering minimum and maximum budget and area values. The condition set is that the maximum value should be greater than the minimum value for both budget and area. This condition is checked when the form i ...

What is the best method for extracting a specific value from this JSON data?

Trying to extract the text value from a JSON response? Wondering how to retrieve the 'text' field, specifically looking for "Киргизия, Бишкек, Чуйский проспект, 213" ?? { "response":{ "GeoObjectCollection" ...

Ionic (Angular) experiencing crashes due to numerous HTTP requests being made

My template contains a list of items <ion-list class="ion-text-center"> <div *ngIf="farms$ | async as farmData"> <ion-item (click)="selectFarm(farm)" *ngFor="let farm of farmData" detail=&quo ...

Seeking assistance for my dissertation assignment: electron, express, and SQLite3

I am currently dedicated to my thesis project, which involves designing an educational desktop video game for both public and private schools within my city. Being a fan of electron, I thought it would be a great idea to develop my app using this platform ...

Unable to transmit data to CodeIgniter controller through ajax communication

I'm struggling with sending a value from an input element to a Codeigniter controller using ajax. The problem arises because I am using a WYSIWYG editor (summernote), which only allows me to receive the input inside a <script>. However, when I ...

Tips for incorporating jQuery UI into Angular 6

No matter how many methods I have tried from StackOverflow, I cannot seem to get jquery-ui to work in my angular 6 component. Here's what I've attempted: I went ahead and ran npm install jquery jquery-ui to install both jquery and jquery-ui. ...

The issue of "Next.js localStorage not being defined persists, despite attempting to

Despite encountering numerous similar questions, I have not been able to find a solution to my specific issue. This is my first experience utilizing Next.js and TypeScript. I am conducting a mock login with REQRES and storing the token in the localStorage ...

Error: The reference property 'refs' is undefined and cannot be read - Next.js and React Application

Here is my code for the index page file, located at /pages/index.js import { showFlyout, Flyout } from '../components/flyout' export default class Home extends React.Component { constructor(props) { super(props); this.state = {}; } ...