Creating Vue components based on a deeply nested data structure

Is there a way to efficiently utilize a nested object for generating Vue components?

My nested object structure is as follows:

"api": {
  "v1": {
    "groups": {
       "create": true,
       "get": true,
       "item": {
          "get": true,
          "destroy": false
      }
    }
  }
}

I aim to create a form with checkboxes for each value within the object. However, I am facing challenges in binding these values to Vue checkbox v-models.

One approach I attempted involved creating a list of lookup keys like ["api.v1.groups.create", "api.v1.groups.get"], and using a function like the one below to extract the entries:

getPerm (p) {
  return p.split('.').reduce(
    (xs, x) => (xs && xs[x]) ? xs[x] : null,
    this.role.permissions)
}

Unfortunately, this method does not yield the desired reference and only provides the boolean value.

Answer №1

Take a look at my helpful code sandbox where I demonstrate how to flatten a dictionary and create a list from a nested entry: Code sandbox link

(The code was forked from a basic Vue template, so you may still see references to 'chart')

Once you flatten your dictionary, you can easily generate vue components using v-for as usual!

Below is the code I used to flatten the dictionary, which you can also check out on the site:

// Creating a nested object
var nested = {
  "api": {
    "v1": {
      "groups": {
        "create": true,
        "get": true,
        "item": {
          "get": true,
          "destroy": false
        }
      }
    }
  }
}

// Function to determine if we have reached the bottom of the object
const isObj = o => o?.constructor === Object;

// I had to use a class to handle the output in different recursive scopes
class NestedProcessor {
  // Constructor initiates the function and returns the flattened dictionary
  constructor(leveled_dict) {
    this.output = {}
    this.process_dict_recursive(leveled_dict)
    return this.ouput
  }
  process_dict_recursive(leveled_dict, keyList = [], depth = 0) {
    if (isObj(leveled_dict)) { // check if we have hit the bottom
      keyList.push('')
      depth++ 
      for (let key in leveled_dict) { 
        keyList[depth - 1] = key
        this.process_dict_recursive(leveled_dict[key], keyList, depth) // call the function recursively at our new depth
      }
    }
    else {
      // Create our lookup keys
      let path = ''
      keyList.forEach((v) => {
        path += v
        path += '.'
      })
      path = path.slice(0, -1) // Remove the last '.'
      this.output[path] = leveled_dict
    }
  }
}

console.log(new NestedProcessor(nested))
//{
//  "output": {
//    "api.v1.groups.create": true,
//    "api.v1.groups.get": true,
//    "api.v1.groups.item.get": true,
//    "api.v1.groups.item.destroy": false
//  }
//}

Additional Notes:

  • I opted for using a class to handle variable scope within the recursion
  • To determine the end point, I utilized a function from Stack Overflow

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

Tips for concealing passwords and email addresses in URLs within an Express application

http://localhost:3000/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e297918790dd878f838b8edf838081a2858f838b8ecc818d8f">[email protected]</a>&pass=abc123 what is the best way to conceal email addresses and ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

Constantly encountering the issue of receiving an error message stating "Trailing Spaces not Permitted" while working with VueJS

I am encountering an issue in my Vue and Vuetify project where I keep getting the error "Trailing spaces not allowed src\App.vue:39:11" every time I compile in the CLI. Even though I added the comment "/* eslint-disable eol-last */" in my ESlint conf ...

Error: Webpack is unable to load PDF file: Module parsing unsuccessful. A suitable loader is required to manage this file format

I am relatively new to using webpack for my projects. Recently, I wanted to incorporate a feature that involved displaying PDFs. After some research, I came across the "react-pdf" library and decided to give it a try. While everything worked smoothly in a ...

Sending an HTTP POST request from an Angular 2 client to a Node.js server

I am encountering a peculiar issue with sending POST requests to my Node.js server. Although my GET listeners are functioning perfectly, when attempting to send a simple request from my Angular 2 application (port 4200) to the Node.js server (port 443), I ...

Real-time Data Stream and Navigation Bar Location

Utilizing the EventSource API, I am pulling data from a MySQL database and showcasing it on a website. Everything is running smoothly as planned, but my goal is to exhibit the data in a fixed height div, with the scrollbar constantly positioned at the bott ...

Problematic Situation Arising from JavaScript AJAX and NVD3.JS Unresolved Object Error

I am currently in the process of developing a script that will allow me to retrieve data for my chart from an external PHP file. Initially, I attempted manually inputting the data into the chart and it worked perfectly fine. However, when I tried using A ...

The attempt to cast to a number for the value of "[object Object]" at the specified path failed in mongoose

My schema is structured like this: module.exports = mongoose.model('Buyer',{ username: String, password: String, email: String, url: String, id: String, firstName: String, lastName: String, credit: Number, }); Wh ...

Issue with Material-ui Autocomplete: onChange event not firing when value is updated in onHighlightChange

I have been customizing Material UI's Autocomplete by adding a feature that allows users to move options to the input using keyboard events (Arrow keys up and down). Then, the user should be able to select an option by pressing the ENTER key. I am fa ...

Why is JSON ParseError still returned by jQuery .ajax call despite JSON being seemingly correct?

Despite having valid JSON on jsonlint.com, I'm encountering a ParseError. Below is the jQuery code snippet: $.ajax({ url: path, type: 'GET', data: {}, cache: false, dataType: 'json', contentType: 'app ...

Connecting Ag Grid with modules

Unable to link with modules as it's not a recognized attribute of ag-grid-angular https://i.sstatic.net/2zwY2.png <ag-grid-angular #agGrid style="width: 100%; height: 100%;" id="myGrid" class="ag-theme-balham" [mod ...

What is the significance of having multiple route parameters in Express?

The RESTful API provided by cex.io offers a route that can return pairs of all currencies with a variable amount of parameters. In express, how can we achieve similar functionality? Consider the following pseudo code example... app.get('/pairs/:arg ...

Exploring characteristics using DocumentTraversal

My goal is to list out the attributes of elements using DocumentTraversal specifically for IE11. While I have been successful in enumerating element attributes, I am facing an issue when trying to do the same with attributes. The enumeration stops at the f ...

Renaming and destructuring of an array's length using ReactJS

I am working with a reduce function shown below: let el = scopes.reduce ((tot, {actions}) => tot + actions.length, 0); I attempted to modify it as follows, but it appears that this is not the correct approach: let el = scopes.reduce ((tot, {actions.l ...

When a new entry is added to the database, automatically refresh a <div> section within an HTML document

I have a basic webpage that showcases various products stored in the database. My goal is to implement an updater feature where, if a user adds a new product, the page will automatically display the latest addition in a specific div. I attempted to refere ...

Displaying a div when hovering over it, and keeping it visible until clicked

I want to display a div when hovering over a button. The shown div should be clickable and persistent even if I move the cursor from the button into the shown div. However, it should be hidden when moving out of the entire area. I'm unsure about how ...

Is there a way to reload the entire page when clicking on a link in NuxtJS?

I am working on a Nuxt project and I am looking for a way to reload the pages every time a user visits any page for SEO purposes. Is there a way to achieve this using Routers? Currently, my app is set up with the default behavior of NUXT which "renders on ...

The technique for handling intricate calls in node.js

My goal is to create a social community where users are rewarded for receiving upvotes or shares on their answers. Additionally, I want to send notifications to users whenever their answers receive some interaction. The process flow is detailed in the com ...

What is the process for setting up Vue.js and using it in conjunction with Sails JS?

After successfully setting up the backend of my website using Sails JS, I decided to integrate Vue.js into my project. Following the installation of Vue and VueResource through npm install --save, I created an app.js file in my assets/js folder. However, ...

Guide on sending images as props in a Vue.js component (using Vite instead of require due to compatibility issues)

This is the main component <template> <rooms-card roomImage="../../assets/images/room3.jpg" roomType="Duplex Room" roomDescription="Sami double bed 1 guest room 3 windows" roomPrice="$50/night" /> < ...