Troubleshooting recursive function errors in a Javascript menu

//check out this current jsfiddle for more details: http://jsfiddle.net/0ht35rpb/45/

I'm attempting to create a loop through a JSON navigation tree in order to match the alternative language counterpart when a user navigates to a specific page.

//Here is the JSON structure:

{
    "langs" : [
        {
            "lang"  : "de",
            "lines" : {
                // German language menu items and links here...
            }
        },
        {
            "lang"  : "en",
            "lines" : {
                // English language menu items and links here...
            }
        }
    ]
}

My JavaScript functions are designed to handle this scenario based on the current language and URL. For instance, if CURRENTLNG is set to 'en' and CURRENTURL is '/en/services', the function fetchFooterUrls() should return an array with ['/en/services', '/de/dienstleistungen']. However, it encounters issues with retrieving third level navigation counterparts like ["/en/popular-projects/compliance/compliance-eng", "/de/beliebte-projekte/compliance/compliance-pruefung-kmu"].

Your script for navigating through the language pair URLs looks promising, but there may be some errors in implementation that need resolving. It's crucial to ensure the correct handling of children elements within the JSON object for smooth navigation experience.

//If you're a moderator or expert on this subject, your input would be greatly appreciated!

Answer №1

After updating the jsfiddle, the errors related to the recursive function call in the else part were fixed. Check out the updated jsfiddle here

The code has been modified as follows:

if (!obj[k].hasOwnProperty('children') || obj[k].children.length <= 0) continue;
var ret = getUrl(pairUrl, currentLng, enMenu[k].children, deMenu[k].children, obj[k].children);
if(typeof ret != 'undefined') return ret;

// JavaScript code snippet
// defining linkTreeObject with language details and menu items

function getLanguagePair(currentLng, pairUrl) {
  // Function to find URL in JSON tree based on current language
  var enMenu = linkTreeObject.langs[1].lines.menu;
  var deMenu = linkTreeObject.langs[0].lines.menu;

  let obj = {};
  if (currentLng === 'de') {
    obj = deMenu;
  } else {
    obj = enMenu;
  }

  return getUrl(pairUrl, currentLng, enMenu, deMenu, obj);
}

// Testing the functionality of getLanguagePair function
console.log(getLanguagePair("en", "/en/how-it-works"));
console.log(getLanguagePair("en", "/en/popular-projects"));
console.log(getLanguagePair("de", "/de/anleitung"));
console.log(getLanguagePair("de", "/de/beliebte-projekte"));

// Tests that are expected to fail
console.log(getLanguagePair("en", "/en/services/compliance"));
console.log(getLanguagePair("en", "/en/popular-projects/compliance"));
console.log(getLanguagePair("en", "/en/popular-projects/compliance/compliance-eng"));

Answer №2

There appears to be an issue with your recursive function. When the URL does not match during the initial function call, the function is recursively called again but without a proper return statement.

function get_10_recursive(number){
  if(number>=10) return 10;
  else return get_10_recursive(number++);
}

In this scenario, if the number is less than 10, the function will continue to be called recursively until it reaches a return statement. At that point, the stack is unwound and the correct result is returned. However, if you remove the return statement in the third line, the code will execute but only provide the result of the initial call, which is undefined.

The issue lies in your code where placing a return statement inside the for loop interrupts the loop and prevents further checking of subsequent strings. Therefore, it is necessary to store the results of the function calls in a temporary variable and only return it if it is truthy (i.e., not undefined).

Your modified getUrl function should look like this:

function getUrl(pairUrl, currentLng, enMenu, deMenu, obj) {
  for (var k in obj) {
    if (obj[k].link === pairUrl) {
      if (currentLng === 'de') {
        return enMenu[k].link; // retrieve equivalent English link
      } else {
        return deMenu[k].link; // retrieve equivalent German link
      }
    } else {
      if (obj[k].hasOwnProperty('children')){
      var tmp =  getUrl(pairUrl, currentLng, enMenu[k].children, deMenu[k].children, obj[k].children);
      if(tmp) return tmp; // check if successful match found
      }
    }
  }
}

Note: The statement

if (!obj.hasOwnProperty(k)) continue
was removed as it was deemed unnecessary.

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

I am selecting specific items from a list to display only 4 on my webpage

I am trying to display items from a list but I only want to show 4 out of the 5 available items. Additionally, whenever a new item is added, I want it to appear first on the list, with the older items following behind while excluding the fifth item. Despi ...

What are the steps I need to take in order to resolve the

How do I troubleshoot this issue? Error: Failed to load gRPC binary module because it was not installed for the current system Expected directory: electron-v6.0-win32-x64-unknown Found: [node-v57-win32-x64-unknown, node-v72-win32-x64-unknown] This problem ...

Is it possible to utilize a jQuery function to count JSON data based on specific keys and values?

function calculateJSONObjFrequencyByKeyValue(obj, key, value) { var frequencyCount = 0; $.each(obj, function(i, item) { if(obj[i].key == value){ frequencyCount++; } }); alert(frequencyCount); } calculateJSONObjFrequencyByKeyValu ...

Offline parsing of JSON data on Android

Hello everyone, I'm a newbie in the exciting world of Android and I've encountered a problem. I am currently working on an Android project that requires a JSON parser. The challenge lies in obtaining my JSON file from a web service created using ...

Tips on viewing class object values within the `useEffect` hook

App.js import React, { useRef, useEffect } from "react"; import Token from "./Token"; export default function App() { const tokenRef = useRef(new Token()); useEffect(() => { console.log("current index of token: ", ...

Count the number of items in a JSON array in AngularJS with a specific ID

To get the total count of articles in a JSON array, I use the following method: Home.html <div ng-controller="pfcArticleCountCtrl">Number of Articles {{articlecount.length}} items</div> Controllers.js // Calculate total number of articles p ...

Employing AJAX, execute a synchronous function asynchronously (Javascript)

Here's a code snippet for the sync function. I've been calling it inside an Ajax, but apparently it's deprecated because it's synchronous. Is there any way to make it run as if it were asynchronous? Or is there a way to convert it into ...

Emphasize the designated drop zone in Dragula

Incorporating the Dragula package into my Angular 2 project has greatly enhanced the drag-and-drop functionality. Bundling this feature has been a seamless experience. Visit the ng2-dragula GitHub page for more information. Although the drag-and-drop fun ...

What is the best way to initiate a Bootstrap carousel so that it begins with the first image every time a modal window appears

I am in the process of creating my own portfolio to showcase my work. I have implemented a feature where clicking on an image opens up a Bootstrap carousel. However, I'm facing an issue where the carousel doesn't always start with the first imag ...

Is it more efficient to perform data sorting on the client side or the server side?

My current task involves fetching data from a server and showcasing it through GWT on the client side. The use of GWT is flexible - it can be swapped out for Ajax calls or transformed into a standalone application rather than just a web app. One dilemma ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

Express Validator: The Art of Isolating Validation Logic

This query is more focused on structuring code rather than troubleshooting bugs or errors. I am currently tackling request body validation, where the JSON structure looks like this: { "title": "Beetlejuice", "year&qu ...

I'm having trouble loading my Google Maps widget. Everything was functioning flawlessly until I attempted to hide it using the .hide function

After successfully implementing a Google Maps widget, I encountered an issue when trying to toggle its visibility using jQuery. Despite clicking on a div element to reveal the widget, the map fails to load inside the designated container. It seems as tho ...

Could we display an error message from Poloniex through printing it?

Attempting to transfer crypto currencies from my Poloniex wallet to external wallets using Python with the Poloniex module has been successful with the following code: from poloniex import Poloniex from poloniex import PoloniexCommandException polo = Polo ...

The JSON.stringify() function helps to convert data into a JSON-formatted string, avoiding any potential "c

connection.query( 'SELECT DeskName FROM desks WHERE stat = ?',["Booked"], function(err, rows){ if(err) { throw err; }else{ try{ var dataToParse = new Array(); dataToParse = rows; res.render('workspaces.html',{parsedArray : JS ...

Having trouble with FullCalendar not showing the correct time for events pulled from a

Utilizing FullCalendar () to retrieve events from a MySQL database table using JSON. The calendar is showing the events, but it seems to be disregarding the event times (hours, minutes, seconds). Below is the JavaScript code from the calendar page - <s ...

"Is there a way to extract a specific value from an XML file based on another element

<dataset> <study recNO="0" seriesRecCount="1"> <patientID>123456</patientID> <accessionNumber>M120170428105320</accessionNumber> <patientIDID>35</patientIDID> <studyUID>2.25.1439 ...

Angular.js reports that the custom HTTP response header is missing

Despite Chrome showing the correct POST response headers, my custom HTTP header X-Auth-Token is returning null in the callback function for the POST request. Angular.js seems to only be returning Cache-Control and Content-Type, with everything else showing ...

Accessing QML Functions from JavaScript

Currently, I am faced with a challenge in my app development using Qt. I need to trigger a QML function from JavaScript when a specific event is triggered from my HTML page. I attempted the following method: app.html <html> <head><title& ...

Rendering basic JSON data from the console to an HTML page using Angular

I have been utilizing openhab for sensor monitoring. To extract/inject the items(things), sensor properties, and room configuration through a web interface, I am making use of openhab's REST queries which can be found here - REST Docs. Wanting to cre ...