I need help figuring out how to represent a nested array within an array of objects within my data instance in Vue

Currently, I have a loop that is showcasing a list of items along with their respective sub-items. The data response payload for this operation appears like the following.

I have successfully executed the loop and managed to display it on my frontend design in the following manner:

My challenge lies in properly modeling this structure within my data instance while preserving the integrity of each group (specifically, a permission and its associated sub-permissions). The expected format for the payload to be transmitted to the backend should look as follows:

Answer №1

It seems that when dealing with intricate structures like this one, the key is to steer clear of using 'v-model'. This is because 'v-model' essentially acts as a shorthand for two separate properties (which vary based on the input type): for checkboxes, it's a shortcut for checked and @change, while for text inputs, it represents value and @input, and so forth.

In response to this particular issue, the approach taken was somewhat customized and credit goes to guanzo. Instead of relying on v-model for modeling or binding in this scenario, functions were utilized to accomplish the task.

isPermissionChecked(pName) {
      return this.selected.some((p) => p.name === pName);
    },
    togglePermission(pName, event) {
      const isChecked = event.target.checked;
      if (isChecked) {
        this.selected.push({ name: pName, sub_permissions: [] });
      } else {
        const i = this.selected.findIndex((p) => p.name === pName);
        this.selected.splice(i, 1);
      }
    },
    isSubPermissionChecked(pName, spName) {
      const permission = this.selected.find((p) => p.name === pName);
      return (
        permission && permission.sub_permissions.some((sp) => sp === spName)
      );
    },
    toggleSubPermission(pName, spName, event) {
      const isChecked = event.target.checked;
      const permission = this.selected.find((p) => p.name === pName);
      if (isChecked) {
        permission.sub_permissions.push(spName);
      } else {
        const i = permission.sub_permissions.findIndex((sp) => sp === spName);
        permission.sub_permissions.splice(i, 1);
      }
    },

The above functions were then applied to the inputs in the following manner:

<div v-for="p in permissions" :key="p.name" class="card">
        <div class="form-grop d-flex align-items-center radio-group1">
          <div class="mr-auto">
            <input
              type="checkbox"
              :id="p.name"
              :checked="isPermissionChecked(p.name)"
              @change="togglePermission(p.name, $event)"
              class="mt-2"
            />
            <label :for="p.name" class="mx-2 mt-2">{{ p.name }}</label>
          </div>
          <div>
      </div>

and

   <div class="mr-auto" v-for="sp in p.sub_permissions" :key="sp">
              <input
                type="checkbox"
                :id="p.name + sp"
                :disabled="!isPermissionChecked(p.name)"
                :checked="isSubPermissionChecked(p.name, sp)"
                @change="toggleSubPermission(p.name, sp, $event)"
                class="mt-2"
              />
              <label :for="p.name + sp" class="mx-2 mt-2">{{ sp }}</label>
            </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

Implementing Ajax functionality in MVC 3 to return a partial view

I wanted to express my gratitude for this invaluable site that has taught me so much. Currently, I am working on an MVC3 component where I need to populate a selectlist and upon user selection, load a partial view with the relevant data displayed. Everythi ...

Maintain the fancybox open even in case of ajax errors

I'm having an issue with my code where the fancybox closes automatically after displaying the error message briefly. I want it to remain open so that users have more time to fix their errors. What could be causing this problem? $(document).ready(func ...

Ways to avoid scrolling on a fixed element

Here is the HTML setup I have... body .top .content The issue I am facing is that when scrolling reaches the end of the ul in the .top element, the background starts to scroll. This can be quite disorienting and makes the site slow on tablets. Even ...

Exiting callback function in JavaScript

Is there a way to retrieve the return value from within a node.js/javascript callback function? function get_logs(){ User_Log.findOne({userId:req.user._id}, function(err, userlogs){ if(err) throw err; if(userlogs){ ...

Comparing two JSON arrays with missing keys

I am working with two JsonArrays that contain data from an API. API 1 [ { "id":1, "value":270 }, { "id":2, "value":1432493 }, { "id":3, "value":63 }, { "id":5, "value":412 }, { ...

What is the process for integrating MongoDB into Vue.js 2?

I've been trying to install mongodb through npm, but I keep encountering the error message "Cannot find module 'fs'." Here is a snippet of my code: <script> const MongoClient = require('mongodb').MongoClient; export defau ...

Toggle the visibility of the identical div

I am facing a challenge with dynamically hiding and showing various div elements on my website. I have managed to achieve this using show/hide, but the issue arises when I need to show/hide some of the same fields repeatedly. The script works fine on the f ...

Is it possible to execute PHP without using Ajax when clicking on a Font Awesome icon?

So, besides using Ajax, is there another solution to achieve the same result? Can a font-awesome icon be turned into a button without Ajax? In case you're unfamiliar with what I mean by a font-awesome icon, here's an example: <i id="like1" on ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...

Update MYSQL table values using AJAX and jQuery, then dynamically refresh the updated values on the web page

Hey there! I am fairly new to utilizing ajax and encountering some difficulty with a fundamental concept. In my MySQL table called "users," I have various user information stored, including the balance they pledge to donate. My goal is to create a div elem ...

form controls disappear upon adding form tags

Currently experiencing an issue with angular and forms that I could use some help with. I have a dynamic form that is functioning properly, but now I need to add validations to it. After following this guide, I established the structure correctly. Howeve ...

The V-Model is failing to bind with the jQuery mask

Currently, I have a form that uses v-model for phone input along with a mask library. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js" type="text/javascript"></script> <input type="tex ...

Attempting to construct a .csv file in PHP using an array

I need help converting the array below into a .csv file format, where the questions are placed in the first row, corresponding answers in the second row, and a Timestamp with the current time at the beginning. This is my attempt: <?php $qna = [ ...

When you download a file through the unpkg CDN, the size of the npm package is

I am experiencing a discrepancy with the file size of a file in my npm package. The file is 307kb in size, but when I download it through unpkg, the same file is only 73.2Kb. I find it quite puzzling how the file can be smaller when downloaded over the net ...

Errors in vue.js conditions

I am currently attempting to validate whether my variable is empty. Despite reviewing my code, I am facing issues with its functionality. My current version of vue.js is 2.5.13 Below you can find the snippet of my code: <template> <div v-if ...

Experiencing Challenges with JavaScript Implementation Within an HTML Document

Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-3.3.1.js"> </script> <script type="text/javascript"> $(function() { alert("Hello World"); }); </script> <meta charset ...

Troubleshooting: JavaScript Bookmarklet Fails to Execute on Certain Websites

Recently, I created a unique bookmarklet that functions flawlessly on some websites, but unfortunately fails to work on others. Interestingly, even when it doesn't work, the script is still added to the bottom of the page; however, only a portion of t ...

reorganize php array structure

I currently have an array that looks like this: Array ( [1] => Vice President [3] => Secretary [5] => Treasurer ) My goal is to transform it into this format: Array ( [0] => Vice President [1] => Secretary [2] => Treasurer ) I attempt ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...