Traverse through an array or object using recursive render functions in JavaScript

Here is an example of the issue I am currently trying to solve: https://codepen.io/wombsplitter/pen/KyWKod

This is the structure of my array:

[{
 //obj 1
 link: [{
        //obj 2
        link: [{
              //obj 3
              }]
        }]
}]

The array has the ability to contain any number of elements at different levels. My goal is to recursively navigate through the array and, using a rendering function, display them on the page while maintaining their original structure.

div.item
  div.info
  div.link
     div.info
     div.link
        div.info
        div.link
           div.info
           div.link

I would greatly appreciate any help or advice on how to achieve this.

Answer №1

How about considering this alternative approach:

generateContent(handler, array) {
  return establishPattern(this.example, handler)
}

// located outside of the App entity
function establishPattern(example, handler){
  return handler('section', { style: 'result'}, example.map(e => {
    return handler('div', {class: 'description'}, [e.label, establishPattern(e.elements, handler)]);
  }))
}

Please note that this method assumes there are no repeating elements in your dataset.

Answer №2

There seems to be a mistake in your code below. You are calling `arr.map` instead of `this.test.map`.

    renderContent(element, arr) {
      return element('div', { class: 'link'}, arr.map(item => {
        return element('div', item.name);
    }

Answer №3

If you simply desire the values, you can achieve it in the following way:

function obtainValues(collection){
  var result = [];
  function recursiveFunc(input){
    var item;
    if(input instanceof Array){
      for(var index=0,length=input.length; index<length; index++){
        item = input[index];
        if(typeof item === 'object' && item !== null){
          return recursiveFunc(item);
        }
        else{
          result.push(item);
        }
      }
    }
    else if(typeof input === 'object' && input !== null){
      for(var key in input){
        item = input[key];
        if(typeof item === 'object' && item !== null){
          return recursiveFunc(item);
        }
        else{
          result.push(item);
        }
      }
    }
    else{
      result.push(input);
    }
    return result;
  }
  return recursiveFunc(collection);
}
var dataObject = {
  el: '#app',
  data: {
    test: [{
      name: 'parent',
      link: [{
        name: 'child1',
        link: [{
          name: 'child2',
          deepObj: {
            deepProp:'Number 7 test',
            num:7,
            deeperArray:[true, false, 'test', 'in', 'here', 1]
          }
        }]
      }]
    },
    {
      name: 'parent2'
    }]
  }
}
var values = obtainValues(dataObject);
// obtainValues brings back an array, hence the .join()
console.log(values.join(', ')); console.log(values);

Answer №4

A simple solution is as follows:

function generateHTML(obj){
   var code = ['<div class="info"></div>'];
   code.push('<div class="link">')
   if(!!obj.link) code.push(generateHTML(obj.link[0]));
   code.push('</div>')
   return code.join('')
}

document.getElementsByClassName('item')[0].innerHtml = generateHTML(obj[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

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...

What is the process for assigning default values to dynamically generated form elements?

I have been working on building a single-page application (SPA) using JavaScript and jQuery. During the process, I encountered an issue with a dynamic form. The user is able to add specific fields as needed, but if they don't generate and utilize all ...

Tips for obtaining response headers

Currently, I am utilizing Angular version 15.0 and retrieving a list of items from the backend (ASP.NET Core 5) with an additional item attached to the header. The GET method in the client-side service is as follows: /** GET Paged commodities from the s ...

Explore the comparison feature with jQuery's combobox

I am attempting to compare values from an array with values in a combobox using jQuery, but I am encountering difficulties. My array is structured like this: (value 1, value 2,...) names separated by commas (Example: john smith, peter pan). On the other h ...

Ways to expand a Bootstrap input field by clicking on it:

I have successfully created a search bar in my navbar, but I am looking to add functionality that allows the input field to expand to its normal size when clicked. I believe this will require some JavaScript implementation, however, I am unsure how to proc ...

How to toggle between displaying divs using JavaScript and Jquery

How can I use JavaScript to show or hide specific divs on page load and upon clicking different links? I want to display the "houseImages" div by default, while hiding the "landImages", "renovationImages", "UpcomingImages", and "voteForNext" divs. Then, w ...

Error message: Parameters are not defined in the Next.js

Struggling to retrieve the endpoint from a specific page in my Next.js application using URL parameters. Despite being able to view the endpoint in the browser, it keeps returning as undefined. I attempted utilizing usePathname from next/navigation, which ...

Troubleshooting Vue 3 Computed Property Not Updating

I'm currently facing a challenge while developing a login form using Vue 3. I am having difficulty in getting the state to update 'realtime' or computed. When attempting to login a user from the template, the code looks like this: <button ...

Dealing with customized protocol responses in JavaScript

My web server is set up to return a response like: HTTP/1.1 302 Found message://ActualMessage While this setup works seamlessly for UI clients like Android and iOS, I'm faced with the challenge of handling this case on a web browser. For instance, ...

I'm having an issue with my Bootstrap tabs - they seem to be unresponsive when clicked

I've been working on a Bootstrap website and have run into some issues that I can't seem to resolve. One problem I encountered was with a set of tabs that were supposed to be interactive, but for some reason, they weren't working as expected ...

Error occurs in Javascript when attempting to execute javascript code using PHP's echo and an unexpected identifier token is encountered

Currently, I am trying to insert a div into the page when a specific condition is met in PHP: if ($var == 0) { echo '<script>console.log("Test."); var res = document.getElementById("response"); res.innerHTML = "<div class='h ...

How can we set up Node JS to automatically trigger events when a specific future date and time from the database is reached?

I have taken on the challenge of providing users with a feature where they can select a date and time in the near future while placing an order. This chosen time and date will be saved in the database. How can I set up a function to automatically execute ...

JSON payload with an array that includes nested JSON objects

I am struggling with JSON objects and need to create a JSN structure similar to the following: { name: 'root', children: [ name: 'son1', children: [....] ] } Could someone please guide me on how to construct it using Java ...

The step-by-step guide on passing arguments and fetching results from Angular UI Bootstrap Modal through Components

I am facing a simple scenario where I have defined a modal as a component and opened that modal using `uiModal.open`. However, when I try to pass custom data to the modal using "resolve" in the open method and arguments in the controller constructor, the d ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...

Customize material-ui themes using useStyles / jss

Is it possible to customize the Material-UI theme using styles without relying on !important? const customTheme = createMuiTheme({ overrides: { MuiInputBase: { input: { background: '#dd7711', padding: 10, }, ...