In dire need of assistance with dividing an array into a menu using JavaScript before my brain implodes

With the usage of Javascript, I am dealing with an array structured as follows:

[{"id":171,
"children":
    [{"id":172},
    {"id":170},
    {"id":173}]},
{"id":174},
{"id":175}]

This array is created from a nestable jQuery list.

Now, I have the requirement to push this array into another one that has the structure of id, top_menu, and submenu entries.

I have attempted around 15 different loops in order to identify commas and determine whether it's a top_menu or sub_menu item based on what comes before the comma. However, all my attempts have failed at some level or another.

Is there a specific function that could simplify this process?

Currently, I am using str.split(',') to locate commas and then applying search and substr methods to establish the menu hierarchy. Any assistance on this matter would be greatly valued.

Answer №1

let navMenu = [
    {"id": 171,
     "children": [{"id": 172}, {"id": 170}, {"id": 173}]},
    {"id": 174},
    {"id": 175}
];

for(let item of navMenu){
    console.log(item);
    if(item.children){
        //submenu logic here
        console.log(item.children);   
    }
}

I believe there is room for improvement in my syntax, although it effectively parses a nested array.

Answer №2

After some troubleshooting, I successfully resolved the issue by restructuring the string in a way that made it easier to add to the array.

Here is the modified code:

var str='[{"id":170},{"id":171,"children":[{"id":172},{"id":173}]},{"id":174,"children":[{"id":176},{"id":177}]},{"id":175}]';

for(var d=0; d<str.length;d++){
  if(newstr!=''){str=newstr;}           
    var childrenstart=str.indexOf("children");
    if(childrenstart!="-1"){
       var endstr=str.substr(childrenstart).indexOf("]");;
   var childrenstring=str.substr(childrenstart,endstr);
   var cleanchildrenstr=childrenstring.replace(/children":/gi,'');
   var newchildrenstrng=cleanchildrenstr.replace(/id/gi,'child');
   newstr=str.substr(0,childrenstart-1)+newchildrenstrng+str.substr(childrenstart+endstr);
   d=childrenstart+endstr;
 } else {
   d=str.length;
 }
}

 var finalstr=str.replace(/{/gi,'');        
 var finalstr=finalstr.replace(/}/gi,'');       
 var finalstr=finalstr.replace(/]/gi,'');       
 var finalstr=finalstr.replace(/\[/gi,'');      
 var finalstr=finalstr.replace(/\"/gi,'');

Although this code could be optimized for efficiency and readability, it serves its purpose as a first iteration. It outputs a string containing:

id:170,id:171,child:172,child:173,id:174,id:175

This resulting string can now be segmented and added into the array.

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

Modifications made to the process module in one file are not reflected in a different file

It seems that the process module in NodeJS is not global, resulting in changes made to it in one module not reflecting in other modules. To confirm my findings, I wrote a small piece of code. Here is the snippet: server.js import app from "./app.js& ...

Achieving the resolution of a Promise amidst the failure of a separate promise

I need to handle a situation where a promise is resolved regardless of the success or failure of an ajax call. I attempted to use the following code snippet: new Promise(function(resolve, reject) { $.ajax({ url: "nonExistentURL", headers: { ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

Step-by-step guide for implementing an "on change" event for a select box within a dialog box

I recently wrote an HTML code snippet like this: <div id = "dialog-1" title = "Dialog Title goes here..."> <select id= "lang" name= "lang"> <option value="1"> TEXT </option> <option value="2"> HTML </op ...

Tips for retrieving the clicked word in JavaScript

Is it possible to retrieve the word that was right-clicked on along with its x, y coordinates? I attempted the following code:document.onclick=getTextOnClick; function getTextOnClick(e) { console.log(e); if (window.getSelection) { txt = wi ...

Interact with Datatable by clicking on the table cell or any links within the cell

When I am working with the datatable, I want to be able to determine whether a click inside the table was made on a link or a cell. <td> Here is some text - <a href="mylink.html">mylink</a> </td> Here is how I initialize my da ...

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

Enhance Data3 Sankey to disperse data efficiently

There are a few instances where the D3 Sankey spread feature is showcased here. However, it seems that this specific function is not included in the official D3 Sankey plugin. Is there anyone who can assist me in obtaining the code for the Spread function ...

Create a JavaScript code snippet that replaces the innerHTML of the function document.getElementById with

In my limited knowledge of JavaScript, I have come across an issue with the following code: function example() { document.getElementById("example").innerHTML = "<script>document.write(example)</script>"; } Unfortunately, this code doesn&ap ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Utilize Node.js to traverse an array of objects and extract particular values to create a separate array

Looking to extract scores from the ratings array for each object and compile them into a new array. For instance, for post with post_id: "5e1223c2383ce049d8b32eb5", the associated array should be [1, 4]. And for the post with post_id "5e146b993dde720850c1 ...

Firebase 9: Access Denied - Realtime Database Security Breach

Currently working on a chat application using Vue3 and Firebase 9, everything is functioning well except for the delete function. An error message appears in the console: @firebase/database: FIREBASE WARNING: set at /message/-MzxBJXezscUw4PbEAys failed: pe ...

Determine the exact scroll position needed to reveal the element when scrolling in reverse

I'm looking for a way to make my div disappear when I scroll down and reappear immediately when I start scrolling back up. Currently, it only works when I reach a certain position instead of taking effect right away. I need assistance in calculating t ...

Exporting Canvas data without the alpha channel

I am looking for a way to resize images that are uploaded in the browser. Currently, I am utilizing canvas to draw the image and then resize it using the result from the toDataURL method. A simplified version of the code (without the upload section) looks ...

How can I retrieve both the keys and values of $scope in AngularJS?

Here is the code I have written to retrieve all key values using $scope. $scope.Signup={}; $scope.Message=''; $scope.SubmitPhysicianSignup = function() { var url = site_url + 'webservices/physician_signup'; //console.lo ...

Using NodeJS and Express: redirection fails to load the specified endpoint

My current project involves a simple e-commerce web application running on localhost built with nodejs and express. Admins are required to register in order to gain access to functionalities such as adding, editing, and removing products from the product l ...

Ways to modify the color of the legend text in a HighChart graph

Click here https://i.sstatic.net/iuPs4.png I am attempting to modify the color of the series legend text from black to any color other than black: $(function () { $('#container').highcharts({ legend: { color: '#FF0000', ...

Enhance Image Size with a Custom React Hook

I've created a function to resize user-uploaded images stored in state before sending them to the backend. const [file, setFile] = useState(null) function dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].ma ...

Navigate through a series of div elements using Jquery

I need help figuring out how to make the window scroll between different divs in a sequence. The issue is that my current code only works for one specific div at a time. $('.down_arrow').click(function(e){ $('html, body') ...

Unidentified Error in Swift Programming Language

I am encountering an issue with a variable called row in my Swift code. The error message says "use of unresolved identifier 'row'". override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let url = N ...