Repetitive process in JavaScript

I am struggling to write certain attributes to HTML using a recursive loop and I can't seem to get the code to work properly.

The JSON data consists of an array of hashes with the following attributes: serno (serial number), parent_serno (serial number of parent), and name (name of the attribute). My goal is to first display each hash.name where "parent_serno == 0" and then, for each one, list the names of hashes where "parent_serno = serno(of the first hash)" to group them accordingly based on serno and parent_serno.

Can anyone help me identify what I'm doing wrong?

var dataBase = [{"serno": 1, "parent_serno": 0, "name": "Home"},
            {"serno": 2, "parent_serno": 0, "name": "Search"},
                {"serno": 10, "parent_serno": 2, "name": "Search Payment"},
            {"serno": 11, "parent_serno": 2, "name": "Problematic Search Payment"},
            {"serno": 12, "parent_serno": 2, "name": "Cash Error"},
            {"serno": 13, "parent_serno": 2, "name": "Payment Note"},
            {"serno": 89, "parent_serno": 2, "name": "Search Payment By Category"},
            {"serno": 131, "parent_serno": 2, "name": "Search Payment New"},
            {"serno": 3, "parent_serno": 0, "name": "User Mangement"},
            {"serno": 4, "parent_serno": 0, "name": "Service Provider"},
            {"serno": 5, "parent_serno": 0, "name": "General"},
            {"serno": 88, "parent_serno":...

Answer №1

 parent = dataBase[i].serno;
 funkcia(parent);

The issue lies in the way you are manipulating the parent variable. As a result, the for-loop continues searching for an incorrect parent value.

To resolve this, you can either assign a different variable:

function funkcia(otherParent) {
    for (var i=0; i < dataBase.length; i++){
        if (dataBase[i].parent_serno == otherParent){
            document.write(dataBase[i].name);
            var new_parent = dataBase[i].serno;
            funkcia(new_parent);
        }
    }
}

Alternatively, you could update the function as follows:

function funkcia(parent) {
    for (var i=0; i < dataBase.length; i++){
        if (dataBase[i].parent_serno == parent){
            document.write(dataBase[i].name);
            funkcia(dataBase[i].serno);
        }
    }
}

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

Converting PHP variables to JavaScript variables: A step-by-step guide

I'm trying to figure out the most efficient method for retrieving PHP variables using AJAX and then transforming them into JavaScript variables. Imagine I have the following code in my PHP file: echo $total; echo $actual; Edit: JSON echo json_enco ...

What is the best way to send an array of grouped data to a table

Here's how I organized the array: { "2023-10-01": [ { "emp_id": 1, "name": "Aruna", "code": "DO", "date": "2023-10-01" }, { &qu ...

Error: A SyntaxError was encountered due to a missing closing parenthesis after an argument list while writing JavaScript within PHP code

I'm facing an issue writing JavaScript within PHP code. Here's my script : echo ' <script>'; echo ' $(function(){'; echo ' x = parseInt($("#counter2").val());'; echo ' $("#add_row2").click(function(){&apo ...

Is there a way to incorporate an animated element within the track of my circular progress bar?

My circular progress bar features two paths, with one path increasing in length as data is received, eventually turning the entire circle red. Here is the SVG HTML code: <path d="M 50,50 m 0,-47 a 47,47 0 1 1 0,94 a 47,47 0 1 1 0,-94" stroke="#A9B0B7" ...

The offspring of a React component

How can I select a specific div in children using React without passing it as a prop? I want to transform the code snippet from: <Pane label="Tab 1"> <div>This is my tab 1 contents!</div> </Pane> to: <Pane> <div&g ...

Steps to send a table to PHP and store it as a text file

I have this program for a form data entry. It includes text boxes to input values, and upon clicking 'Submit', the input values should be displayed below while resetting the text box for another set of inputs. The issue I am facing is with the sa ...

What is the best way to show the contents of an array after making a getjson request?

My function makes two getJSON calls and writes the responses to an array. At the end of the second getJSON call, I used the code snippet below: alert(files.length); print_r(files); console.log(files); However, the alert shows the correct number of items ...

Using SWR, retrieve data in client components consistently for each request in a Next.js version 13.3 environment

I recently upgraded to Next.js 13.3 with the app dir set up. I have a simple component that displays the current date. However, it only updates the date once and then doesn't update again until I rebuild the app. In Next.js 12, the date would update w ...

Understanding the inner workings of a Mongoose model without the need for

server.js process.env.NODE_ENV=process.env.NODE_ENV || 'development'; var mongoose=require('./config/mongoose'); express=require('./config/express'); var db=mongoose(); var app=express(); app.listen(3000,function(){ ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

Get the npm distribution package without the need to actually install npm

Is there a way to obtain an npm package without the need for running npm view XXX ... or installing node/npm? Specifically, I am attempting this process on a Linux operating system. ~UPDATE~ I now understand that I should have provided more details about ...

Transform buffer information into a visual representation

How can I convert the buffer data into an image so that when I loop through the results and render it in the img src, the user will be able to see the image? I am currently using ejs for rendering. <span> <img class="user-with-avat ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

What is the best way to implement asynchronous image loading on hover events in React.js?

You may have come across this type of effect before. A good example can be found here - https://codepen.io/anon/pen/GEmOQy However, I am looking to achieve the same effect in React. While I understand that I can use the componentDidMount method for AJAX c ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

Form submission is failing due to a single checkbox not being submitted and an error is occurring with MultiValueDictKeyError during

<body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/"> {% csrf_token %} <div class="form-group" ...

Creating an HTTPS server that can be accessed via my specific IP address

My attempt to create ad hoc and OpenSSL based certificates in Python Flask was inspired by a tutorial I found on this website. I also explored the method of creating root CA, trusting it, and generating certificates as outlined on this GitHub thread using ...

Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score. The goal is to have the mod ...