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

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

error TS2304: The term 'MediaRecorder' is not recognized

How can I add audio recording capability to my Angular application using media recorder? Unfortunately, I am encountering the following error: Error TS2304: 'MediaRecorder' cannot be found If anyone knows a solution for this issue, your help w ...

I'm experiencing some issues with the JavaScript setTimeout function - can anyone help troubleshoot

in my quest to find a way to hide the notificationBar without the use of a button and using XX.hide() oncomplete, I stumbled upon a javascript snippet <script type="text/javascript> jQuery(function() { bar.show(); setT ...

Dealing with Sideways Overflow Using slideDown() and slideUp()

Attempting to use slideUp() and slideDown() for an animated reveal of page elements, I encountered difficulty when dealing with a relatively positioned icon placed outside the element. During these animations, overflow is set to hidden, resulting in my ico ...

I love the idea of the music playing on as I navigate between pages or tabs. Such a cool feature with Next

I'm looking to implement a music player within my next.js application. How can I ensure that the currently playing track doesn't stop when switching between pages? Essentially, I want the music playback to continue seamlessly as users navigate th ...

Variable declared in $scope suddenly losing its definition

Within my directive controller, I've implemented a $watch function as follows: $scope.$watch(function () { return service.abc; }, function(newVal, oldVal) { $scope.abc = {abc: newVal}; }); However, I've encountered issues with the variabl ...

What is the functionality of the Poloniex JSON API web links?

For the past few months, I have been attempting to retrieve historical data for a specific pair at 4-hour intervals. A format was suggested to me to fetch this data: Is there a way to specify duration and time interval using the provided links? The link ...

The user is defined, but the user's user ID is not specified

It seems that the user is defined, but user.user_id is not. My framework of choice is express.js and passport.js. router.post('/requestSale', function(req,res){ console.log('session user: ' + req.session.passport.user); //logs ...

Incorporating JSON into a ColdFusion program

I have a website that showcases different views for registered and non-registered users. I am currently redesigning the product navigation to make it easier to manage by using JSON format. My website is built on Mura CMS with ColdFusion. Although what I ...

What is the best way to utilize a JavaScript function across all pages in Drupal 7?

What is the best way to utilize a global JavaScript function in Drupal 7? I have structured my JavaScript file as follows and included it using drupal_add_js(): (function($) { function add_if_country_is_not_usa() { // Determine the current country ...

Obtaining Asynchronous JavaScript responses with Selenium Webdriver

We recently integrated an asynchronous JavaScript call into our website. I am currently working on configuring Selenium Webdriver to pause and wait for a response from this particular call. The event listener code snippet is as follows: $(document).on("a ...

Deciphering deeply nested JSON data using Python and Pandas

My goal is to extract information from a JSON response and convert it into a dataframe for export to a .csv file. The JSON response structure includes the following fields: { "count":2, "next":null, "previous":null, "results":[ { ...

Is it recommended to utilize JSON in conjunction with jQuery and AJAX within a PHP file?

I've never had the chance to work with json before and honestly, I'm pretty clueless about how it functions. I'm looking to utilize jquery for making ajax calls to a php file. Is it recommended to use json in this scenario? I've heard t ...

I'm still searching for a proper solution on how to access JavaScript/jQuery functions within Colorbox

For my website, I am utilizing PHP, jQuery/JavaScript, Colorbox (a jQuery lightbox plugin), Smarty, and other tools. Currently, I am working on displaying data in a popup using the Colorbox plugin. However, I am facing an issue with calling a JavaScript fu ...

Assistance with JSONP (Without the use of jQuery)

I've been putting in a lot of effort trying to understand how to make a JSONP request, but all the reference materials I find are full of jQuery examples. I can go through the jQuery source code, but I prefer a straightforward and simple example. I&ap ...

My goal is to transfer information from the client-side to the server-side upon the user disconnecting from a socket.io connection using Node.js

Is there a way to transmit data from the client side to the server side when a user disconnects from a socket.io connection in Node.js? I attempted creating a new event and calling it within the 'disconnect' event, but it seems impossible since t ...

Material UI - Radio buttons do not properly reflect the current state of the value

I'm diving into the world of full stack development and I'm working on a project to enhance my understanding of frontend programming with React JS and Material UI. Specifically, I've created a Dialog component to send data to the backend, bu ...

Intent not reachable within AsyncTask context

Apologies for my poor English, but I have encountered an error with the AsyncTask class. When calling intent from PostExecute method in Main_Activity, I am getting a "Not Enclosing Instance type is accessible in scope" error. package com.example.pfc; im ...