Set options for nested arrays with up to n levels of children

My project involves building a category module using Laravel for the backend and Vue.js for the frontend.

I have incorporated the library Laravel Nestable

The library has been successful in producing the desired output.

[
  {
    "id": 1,
    "name": "Category One",
    "slug": "category-one",
    "child": [
      {
        "id": 2,
        "name": "Category Two",
        "slug": "category-two",
        "child": [
          {
            "id": 3,
            "name": "Category three",
            "slug": "category-three",
            "child": [],
            "parent_id": 2
          }
        ],
        "parent_id": 1
      }
    ],
    "parent_id": null
  }
]

However, I am facing an issue on how to use this nested array to multiple depths for the options in Vue. For instance:

<option value="1">Category One</option>
<option value="2">-Category Two</option>
<option value="3">--Category Three</option>
<option value="4">---Category Four</option>
<option value="5">Category Five</option>

The desired display above cannot be obtained with:

<option v-for="category in categories" value="category.id">{{category.name}}</option>

If you have any solutions or suggestions, kindly share them with me.

Answer №1

Here is a method to include a dash in the data using parent_id:

<option v-for="category in categories" value="category.id"><span v-if="category.parent_id">{{getDash(parent_id)}}</span>{{category.name}}</option>

new Vue({
    ...
    computed: {
        getDash: function (parentId) {
          let string = '';
          for(let i = 0; i < parentId; i++) {
            string += '-'
          }
          return string;
        }
    }
    ...
})

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

JavaScript seems to have difficulty correctly parsing objects from JSON

Having trouble populating a Repeat Box with objects from a JSON document. Despite my efforts, it keeps duplicating the first item instead of adding each one individually. Any ideas on what might be causing this issue? Below is the code I am currently usin ...

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

Unable to retrieve data when utilizing SWR and Context API in Next.js

I'm currently working on fetching data from an API using SWR and dynamically setting the currency based on user preferences through context API. However, I'm facing issues as I am unable to view any data. Can someone please provide assistance or ...

Preventing FlatList from scrolling when re-sizing

Resizable from the re-resizable package is causing my Flatlist not to scroll properly. Despite having enough elements to trigger scrolling, it fails to do so when the resizable element is present. This issue does not occur when the resizable element is rem ...

The issue arises when trying to use destructured imports with Mongoose

I've been developing a straightforward Express app with ES6. In the process of creating a schema and model for Mongoose, I encountered an issue with the following syntax: import mongoose, { Schema } from 'mongoose'; const PostSchema = new ...

The method request.getParameter in Servlet may sometimes result in a null

My website utilizes JQuery to make an Ajax call to a servlet. function sendAjax() { $.ajax({ url: "/AddOrUpdateServlet", type: 'POST', dataType: 'json', ...

Exploring Node.js with the power of EcmaScript through Javascript Mapping

I am currently using Map in NodeJS version 0.10.36 with the harmony flag enabled. While I am able to create a map, set and retrieve data successfully, I am facing issues with other methods such as size, keys(), entries(), and forEach as they are returning ...

mention the element to display on the pagination

I find the logic here quite puzzling. This particular code block seems to be related to pagination, as it involves a function that is triggered upon clicking. componentDidUpdate() { const { location } = this.context; const { query } = this; if ...

Setting up a basic webhook server with Node and Express

I'm struggling to locate comprehensive tutorials on webhooks for beginners. Being new to this concept, I have only come across basic explanations of how they operate. Our current requirement is to inform users of our APIs about new records. With Kafk ...

Rearrange the layout by dragging and dropping images to switch their places

I've been working on implementing a photo uploader that requires the order of photos to be maintained. In order to achieve this, I have attempted to incorporate a drag and drop feature to swap their positions. However, I am encountering an issue where ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

Is there a way in JavaScript to convert a web page into a string?

I'm looking for a way to retrieve the HTML content of a webpage using JavaScript, even if it's on a different domain. Similar to what wget does but in JavaScript. I intend to use this for web crawling purposes. Could anyone guide me on how to fe ...

javascript, contrasting functions and variables

As I delve into the world of Javascript and JQuery (hence why I chose the example below), I have observed an interesting behavior. I noticed that not only can I define a function and call it, but I can also just do something else mysterious by using the do ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

Is it possible to remove the address bar from appearing on a browser when a page loads?

I am in the process of developing a customer wifi landing page, and although we have made progress with ensuring it is the first page that loads, I want to take it a step further. My goal is to require customers to agree to our usage policy before gaining ...

The getStaticProps() function is failing to send data over to the components

I am currently learning how to use Next.js by following the guide on nextjs.org. My question is, when I use the getStaticProps function, it seems to fetch and log the data correctly inside the function. However, when I pass the data (which is the props ob ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

Creating a callback function within its own definition

I need help with my download function that is calling a callback to "downloadCallback". Is it possible to define the downloadCallback function inside the download function itself? If so, how can I achieve this? Below is the implementation of the download ...

Javascript will not recognize or interpret PHP's HTML tags

When PHP sends HTML strings to HTML through AJAX wrapped in <p class="select"></p> tags, the CSS reads the class perfectly. However, JavaScript/jQuery does not seem to work as expected. Even when trying to parse <p onclick="function()">&l ...

Unable to successfully transfer parameters from AJAX to PHP

I successfully utilized Jquery UI to update the position of my table. Now, I am trying to pass a parameter from AJAX to PHP in order to update my database with the current table position. However, I encountered an issue where I receive a TypeError: data=nu ...