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

Can someone please help me figure out why the "setInterval" function in my script isn't functioning as expected?

I've been experimenting with controlling the refresh rate of drawn objects in a canvas using JavaScript. Even after going through the tutorials and examples on w3.school, I'm still unsure why the "setInterval" function is not executing the "gener ...

Utilizing a single variable across different JavaScript scripts - where one script includes a .ready function while the other does not

I am facing a challenge with 2 javascript scripts that I have: <script type="text/javascript"> function capture(){ var canvas = document.getElementById('canvas'); var video = document.getElementById('video'); canvas.getContext ...

Is it possible to utilize Dictionaries (key, value) collections with JQuery?

Is jQuery capable of supporting a collection of Dictionaries which consists of keys and values? I am interested in organizing the following data into a structured format: [1, false] [2, true] [3, false] This structure should allow for adding, looking up ...

modify the color of text in a row within a jquery ajax table

Is it possible to change the font color of values in a row based on a condition inside a function? Specifically, if the TotalStudent count exceeds the room capacity, can we add student information to the table with red font color? Below is my attempt using ...

Scroll-triggered Autoplay for YouTube Videos using JQuery

Issue: I'm trying to implement a feature where a YouTube video starts playing automatically when the user scrolls to it, and stops when the user scrolls past it. Challenges Faced: I am new to JavaScript web development. Solution Attempted: I referre ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...

Ways to tidy HTML/XML code?

Upon receiving a web service response, the data appears as such: <text>&lt;span class="TitleServiceChange" &gt;Service Change&lt;/span&gt; &lt;span class="DateStyle"&gt; &amp;nbsp;Poste ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Leveraging an external JSON file within a Vue application

A friend of mine isn't very tech-savvy, so I'm building a website for him with an idea to simplify the process. I plan to create a JSON file to store all the text and image paths, allowing him to easily make changes without needing to delve into ...

Displaying a list of objects in Vue.js using an <a> tag to iterate

I am attempting to loop through a list of objects and display their attributes in the <a> tag For instance: <a href="link.url" target="_blank"><i class="links.fontawsomeicon" alt="link.text"></i ...

store events in a MySQL database using a servlet callback and display them on a full calendar

Hey there! I recently started using the full-calendar jQuery plugin and successfully integrated it into a JSP page. The events on the calendar are loaded from a MySQL database by calling a servlet that generates a JSON array of retrieved elements. Now, I& ...

How can you effectively load shared header and panel HTML onto pages located in separate directories using jQuery Mobile?

I am currently developing a multi-page application utilizing jQuery Mobile and incorporating loadPage() to retrieve various pages. The overall structure is outlined below. landing.html /app-pages/page1.html /app-pages/page2.html /app-pages/page3.html ...

Node.js Express.js Module for Asynchronous SqLite Operations

Currently, I am working on a task that involves making synchronous requests to a database and passing the data to Express. Here is the code snippet: app.get('/', (req, res) => { let db = new sqlite3.Database('./Problems.db'); ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

What is the best method for incorporating information into an existing object when it is currently empty?

When it comes to data removal, my method involves locating the element using findIndex and marking it as a null value in isInArray. However, if no such data exists, how can I add it to an empty element starting from the first one? For instance, if the fi ...

Utilizing Browserify routes and configuring Webstorm

When building my project using gulp and browserify, I made use of path resolution for easier navigation. By following this guide, I configured browserify as shown below: var b = browserify('./app', {paths: ['./node_modules','./src ...

VueJS - Harnessing the power of the Document Object Model for dynamic template rendering

Essentially, I am in need of VueJS to provide warnings for unregistered components when in DOM template parsing mode. It seems that currently Vue does not pay attention to custom HTML when using DOM templates, although errors are correctly displayed with s ...

Tips for transforming the input date value from Mui Datepicker

import * as React from "react"; import moment from "moment"; import TextField from "@mui/material/TextField"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { LocalizationProvider } from &quo ...

What's the reason behind beforeunload not triggering?

I've gone through numerous similar posts, but I'm struggling to figure out what's not quite right with this code snippet: $(window).on("beforeunload", function () { debugger handleBeforeUnload(); return false; }); function handl ...

After swapping out "div" with "input" and then replacing "input" with

My goal is to create a function where a user can edit text within a div. The idea is to replace the current text with an editable input field, and then convert it back into a div after the user hits enter. I've encountered an issue while trying to im ...