Display the keys of a nested array in Vue.js when the structure is unknown

Here is a representation of a dynamic array I have:

 nodes: [
        {
          n1: "Foods",
        },
        {
          n4: "Drinks",
          b7: [
            {
              a2: "Beers",
              a4: [
                {
                  a5: "Budweiser",
                  a6: "example",
                },
                {
                  a7: "Heineken",
                },
                {
                        a8: "1",
                        a9: "2",
                        
                    },
                    
              ],
            },
            {
              z1: "Wines",
            },
            {
              z2: "Whiskey",
            },
          ],
        },
      ]

This array is constantly changing. In order to visualize the key relationships in this array, I want to display them in a tree table. Here's an example of how it should look:

n1
n4
  b7
     a2
     a4
        a5
        a6

Answer №1

I have implemented this solution using pure vanilla JavaScript:

(async () => {
  var nodes = [{"n1":"Foods"},{"n4":"Drinks","b7":[{"a2":"Beers","a4":[{"a5":"Budweiser","a6":"deneme"},{"a7":"Heineken"},{"a8":"1","a9":"2"}]},{"z1":"Wines"},{"z2":"Whiskey"}]}];

  var tree = "";

  // Mapping each Node from the nodes
  async function mapNodes(nodes) {
    nodes.map(async (node) => {
      await mapNode(node);
    });
  }

  // Mapping each key from the Node
  async function mapNode(node) {
    tree += `<ul>`;
    Object.keys(node).map((key) => {
      mapKeys(node[key], key);
    });
    tree += `</ul>`;
  }

  // Handling each key value
  async function mapKeys(elm) {
    if (typeof elm === "string") {
      tree += `<li>${elm}</li>`;
    } else if (typeof elm === "object") {
      await mapNode(elm);
    } else if (Array.isArray(elm)) {
      await mapNodes(elm);
    }
  }

  // Start of the loop
  await mapNodes(nodes);
  // The rendered tree can be viewed by injecting ${tree} variable to the DOM
  document.querySelector("div").innerHTML = tree;
})();
<div></div>

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

Using Phonegap alongside ons-scroller and ons-button

Recently, I have been using Phonegap with the Onsen UI system on iOS devices. I encountered an issue where buttons included within an ons-scroller were not clickable when running on an iPad or iPhone. Here is the code snippet that caused the problem: < ...

I encountered the error message "TypeError: e is undefined" while attempting to make an ajax call

My goal is to showcase a website's content using file_get_contents in a PHP script and ajax on the front-end. I am able to display the entire page successfully, but when attempting to only show a certain number of images, I encounter the "TypeError: e ...

Guide to retrieving SQL data using Node.js with mysql2

I've decided to convert my code from Python to Node.js, and I'm encountering a problem when trying to retrieve data from SQL. In Python, it's simple to get the data, return it, and then use it in the code. Here is the Python code: def sql_g ...

Tips for sending information to a different vue.js component

Incorporating a Vue.js template is my current project. I am seeking ways to pass menuItemsData to another Vue component called timeselect (as depicted in picture 2 where I attempt to push it to a different component). Despite scanning through various tutor ...

Tips for showcasing an array in nested elements within an Angular mat-tree

I'm new to Angular and I need help displaying an array's values within the child elements of a material tree. Specifically, I want to show the names of fruits (such as Apple, Banana...) in the child elements. The colors and discounts from the ar ...

Transferring events and properties between a parent element

Is there a way to efficiently pass props and events down to a re-usable button component without the need to consider all possible options? For instance, if I assign a type to the <new-button> element, can it automatically pass that type on to the u ...

Altering various HTML components with every swipe of SwiperJS

I am new to working with JavaScript and I have integrated a Swiper JS element into my HTML page. Here is the current code I am using: <head> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css&quo ...

Display the Angular UI grid containing data from the textboxes once the information has been submitted

I recently started working on an angularjs application and I am facing some challenges in finding the solution. Any advice or suggestions would be greatly appreciated. My goal is to dynamically display an angular UI-grid based on the text selected in the ...

Displaying API response array object in React application

Currently, I am attempting to retrieve information from an API, parse the response content, and then display it in a loop. However, I have encountered a warning message: webpackHotDevClient.js:138 ./src/App.js Line 20: Expected an assignment or function ...

Using JavaScript Functions to Resize Buttons and Change function on Click

I have a button in my code that triggers CSS changes by adding and removing classes. The JavaScript for this function works as intended - clicking once adds the class, clicking again removes it, and so on. However, I also implemented a feature to remove t ...

Is SSG the best approach for deploying a Nuxt.js dashboard?

We have plans to create an internal dashboard utilizing Nuxt.js. Since this dashboard will be used internally, there is no requirement for a universal mode. Typically, most dashboards are designed as SPAs (Single Page Applications). However, SPAs still ne ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

The carousel is failing to display two items on each slide

I've integrated a carousel library from npm into my project. However, I'm facing an issue where I need to display two cards in each slide within the carousel. Here's a snippet of my code: Catalog.js import React from 'react'; impo ...

A guide to transforming a string into a numerical value using Vue

When this code is executed, it will display the following string: Pressure 770.3157279 mm <div class="info">Pressure {{info.main.pressure * 0.750064}} mm </div> If you want to convert the number to an integer and achieve the output: Pressure ...

Array with multiple dimensions using commas as delimiters

My array (array[]) contains elements in the format below, separated by a comma: array[0] = abc, def, 123, ghi I want to transform this array into another multi-dimensional array (arrayTwo[]), structured like this: arrayTwo[0][0] = "abc" arrayTwo[0][1] = ...

Utilizing jQuery and AJAX, execute a PHP query based on the user's input and showcase the query's outcome without reloading the page

For the past 24 hours, I've been on a quest to find a solution. Although I've come across similar inquiries, either the responses are too complex for my specific scenario (resulting in confusion) or they are of poor quality. The crux of my issue ...

The issue with MaterialUI Select's set value is that it consistently falls outside the expected

I'm currently working on a MaterialUI Select component where I am dynamically handling the value parameter. However, I'm facing an issue where even though I set a valid value from the available options, it always shows as out of range. SelectInp ...

What is the best way to incorporate a popover into a fullcalendar event displayed on a resource timeline in Vue while utilizing BootstrapVue?

I need help adding a popover to an event in a resource timeline using fullcalendar/vue ^5.3.1 in Vue ^2.6.11 with ^2.1.0 of bootstrap-vue. Although I found some guidance on Stack Overflow, the solution involving propsData and .$mount() doesn't feel l ...

Interaction between the Vue parent and any child component

I am working with a series of components that are structured in multiple levels. Each component has its own data that is fetched over AJAX and used to render child components. For instance, the days parent template looks like this: <template> &l ...

What is the best way to halt a window.setInterval function in JavaScript?

I have a JavaScript function that runs every 2000ms. I need to find a way to pause this function so that the user can interact with other elements on the page without interruptions. Is there a way to achieve this? Below is the code for the function: win ...