Displaying nested arrays correctly

My latest endeavour involves constructing a data tree in Vue, utilizing components.

Let's examine the provided data snippet:

"data": [
{
  "id": 1,
  "name": "foo",
  "children": [
    {
      "id": 2,
      "name": "bar",
      "children": []
    },
    {
      "id": 3,
      "name": "hulu",
      "children": []
    }
  ]
},
{
  "id": 4,
  "name": "foobar",
  "children": [
    {
      "id": 5,
      "name": "foobar hulu",
      "children": []
    }
  ]
}]

My aim is to present this data in a table format like so:

ID ║ Name ║ Path
1 ║ foo ║ /foo
2 ║ bar ║ /foo/bar
3 ║ hulu ║ /foo/hulu
4 ║ foobar ║ /foobar
5 ║ foobar hulu ║ /foobar/foobar hulu

I have attempted to create a component that recursively calls itself when children are present. However, I encountered an issue with Vue.js only allowing one root element in a template.

Here are my current components:

var Element = {
    props: ['context', 'path'],
    name: 'self',
    template: `
        <tr>
            <td>{{context.id}}</td>
            <td>{{context.name}}</td>
            <td>{{path}}</td>
        </tr>
        <self v-if="context.children.length != 0" v-for="child in context.children" :context="child" :path="path + '/' + child.name"></self>
    `
};

var Tree = {
    components: {
        'element': Element
    },
    template: `
        <table v-if="elements.length != 0">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Path</th>
                </tr>
            </thead>

            <element v-for="element in elements" :context="element" :path="'/' + element.name"></element>
        </table>
    `,

How can I overcome this obstacle? I experimented with enclosing the element template within a tbody, which did accurately calculate the path and display all elements, but resulted in nested rows inside columns which looked unattractive.

https://i.stack.imgur.com/rmeAT.png

Any suggestions or ideas to tackle this challenge would be greatly appreciated!

Answer №1

Flatten the paths.

Vue.component("flat-tree",{
  props:["paths"],
  template: "#flat-tree-template",
  methods:{
    flatter(data, root, acc){
      return data.reduce((acc, val) => {
        acc.push({
          id: val.id,
          name: val.name,
          path: root + val.name
        });
        if (val.children)
          return this.flatter(val.children, root + val.name + "/", acc);
        else
          return acc;
      }, acc);
    }
  },
  computed:{
    flatList(){
      return this.flatter(this.paths, "/", []);
    }
  }
})

Template

<template id="flat-tree-template">
  <table>
    <tr v-for="path in flatList">
      <td>{{path.id}}</td>
      <td>{{path.name}}</td>
      <td>{{path.path}}</td>
    </tr>
  </table>
</template>

Check out the live example here.

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

Angular Link function encounters scope undefined issue

I've been struggling with this issue for some time now. Imagine I have the directive and controller setup as shown below: angular.module('LiveAPP.artist',[]) .controller('artistCtrl', ['$scope', '$http', ' ...

The process of passing $refs in Vue explained

I have a feature where all the data is passed to the child component. Currently, I am able to pass $attrs and $listeners successfully: <template> <el-form v-on="$listeners" v-bind="$attrs" :label-position="labelPosition"> <slot /> ...

Unable to minimize or hide the ace editor widget with Cypress

Today marks the beginning of my journey into posting on this platform, and I am eager to get it right. In my current project using Cypress for writing integration tests, I encountered a challenge while attempting to click on an Ace editor widget within a ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

What are the steps to implementing PNG masking using PixiJS?

I am currently working on incorporating a png sprite as a mask for another layer. I found a demo on the pixi.js official website and created this fiddle: https://jsfiddle.net/raphadko/ukc1rwrc/ The code snippet below is what I am using for the masking fu ...

Capacitor: Building without push-notifications plugin is not possible

I have been attempting to utilize the capacitor push notifications plugin in a quasar project. I followed this tutorial as a guide. However, upon running the command: quasar build -m capacitor -T android, I encountered this error within my quasar project: ...

`The value of an element within an array changes automatically`

In my current setup, I have a traditional array where each element represents an HTML element. The issue arises when I manipulate these elements within the array; any changes made to the HTML element also reflect in the array automatically. However, I pref ...

Developing view logics in Angular using ng-grid/ui-grid

Exploring the possibilities of creating a grid with advanced features such as filtering, resizing, scrolling, fixed headers, row formatting, and cell formatting using AngularJS. After reviewing various grids documentation, I have come across the following ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

Confused about having to use window.variableName in my code and not understanding the reason

Working on a web app with JS, Angular, and Meteor that integrates the Youtube API has been quite challenging. In one of my controllers, I initialized the youtube player object in the constructor following the necessary steps outlined by the Youtube API. Ho ...

Is there a way to have a page automatically send you to a different URL depending on the information included in the link's GET statement?

I am in need of a straightforward piece of code that can automatically redirect a user to a different URL specified within the current URL: For instance: http://example.com/index.php?URL=anothersite The scenario is as follows: a user first lands on http ...

Reading complex table structures with Selenium

Incorporating Selenium into my Java project, I am on a mission to purchase coupons during a test and subsequently display them in the coupon overview. Multiple coupon packages can appear in this area if the user has previously made purchases. The structur ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

React Navigation with Vuetify Button for Menu Bar

I'm currently working on a website and I was trying to customize the styling of v-btn to resemble an active link. While I managed to achieve some success, the background of the button isn't changing correctly. Instead, only the text is getting hi ...

Executing an AJAX request to insert data into MySQL

After my extensive online search, I came across a solution that involves using ajax to set information in my database. While browsing through this page, I learned how to retrieve data from the database. My specific query is: can we also use ajax to set in ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

Issue with jquery's .load() and getScript functions

Earlier today, I encountered an issue with a .load() function being called in a script. I managed to solve the problem using .getScript(), but now I'm facing a major issue - the function is being executed multiple times. You can find the full code a ...

How can I fetch data from a ManyToMany jointable using Typeorm?

Is there a way to retrieve the categories associated with posts when fetching user data? Data Models: @Entity() export class Category extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() name: string; @Column() description: s ...

Ways to access information and functions from another component

Creating a timer dashboard where alarms can change the background color of the timer. Looking to display the timer on a different page with the set background color from the dashboard, but struggling to pass data between components successfully. http ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...