Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value:

<div v-for="group in groups">

   <input type="checkbox" v-model="selected" :value="group">       

   <template v-for="item in group">
      <input type="checkbox" :value="item" v-model="selected">
   </template>
</div>

The 'groups' object is an array of arrays structured like this:

let groups = [
  [
    {id:1, foo1: '...', foo2: '...'}, 
    {id:2, foo1: '...', foo2: '...'}
  ], 
  [
    {id:5, foo1: '...', foo2: '...'}, 
    {id:8, foo1: '...', foo2: '...'}
  ],
];

Each 'item' in the template represents an array. The objective is to append a flat array to the 'selected' model when checkboxes are checked. For example, selecting both dynamically generated checkboxes should result in the 'selected' model containing 4 objects instead of 2 arrays of objects (selected will be

[{id: 1, ...}, {id: 2, ...}, {id: 5, ...}, {id: 8, ...}]
).

This functionality should also work when any checkboxes are unchecked. If the first checkbox is unchecked, the 'selected' model should only include the items from the second checkbox (selected will be [{id: 5, ...}, {id: 8, ...}]).

This feature is necessary for managing the selection and deselection of entire groups of checkboxes.

Is it possible to achieve this behavior in Vue? I haven't found any documentation on this specific scenario. Thank you.

Answer №1

If you're looking to simplify your code, one approach is creating a computed property called flatSelected that takes the selected array and returns a flattened version of it. Here's an example of how you can implement this:

export default {
    ...,
    computed: {
        flatSelected () {
            return this.selected.reduce((acc, cur) => [ ...acc, ...cur ], [])
        }
    }
}

You can then use this computed property in your template like so:

<template>
   <input v-for="item in itemsGroup" type="checkbox" :value="item" v-model="selected">
   <input v-for="item in flatSelected" type="checkbox" :value="item" v-model="flatSelected">
</template>

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

Struggling with an error while experimenting with tensorflow/teachable machine on vuejs

After experimenting with vuejs and , I encountered an issue while trying to export the model for my project. As I adjusted the syntax to fit Vue, I hit a roadblock when the code returned an error stating "cannot read properties of undefined...." console.lo ...

What causes objects to be added to an array even when the condition is not met?

In the process of creating a terminal game using node.js, I am developing a random field consisting of different elements such as hats, holes, and pathways. The player's objective is to navigate through the maze and locate their hat within the field. ...

Setting up scheduled MongoDB collection cleanup tasks within a Meteor application

After developing an app to streamline form submissions for my team, I encountered a problem during testing. Meteor would refresh the page randomly, causing loss of data entered in forms. To solve this, I devised a two-way data binding method by creating a ...

NuxtJS store is not fetching values from local storage correctly and returning them as undefined

In my Nuxt application, I encountered an issue where one of the components in the mounted lifecycle hook is unable to retrieve a value from the state store. This value is stored locally, but for some reason, the store returns it as undefined. Interestingly ...

Update the contents of a div element with JavaScript and PHP combo

When I click on the following div, I want to replace it with a similar one from file.php. The div tag in question is: <div style="display: none;" id="extra" class="container2" xml:id="page"> <div class="title"> <h2>Stuff to check out< ...

The browser has blocked access to XMLHttpRequest from a specific origin due to the absence of the 'Access-Control-Allow-Origin' header in the requested resource

After developing an Asp.Net Core 3.1 API and deploying it on the server through IIS, everything worked fine when sending GET/POST requests from Postman or a browser. However, I encountered an error with the following code: $.ajax({ type: 'GET' ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Contrast between utilizing i < strlen() and str[i] not equal to ''

My code used to generate a time limit exceed error when I implemented it with the syntax for(i=0;i<strlen(s);i++). However, when I changed it to for(i=0;s[i]!='\0';i++), the submission was successful. What could be the reason for this dif ...

"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope. As a beginner in An ...

Getting the values of $scope variables from AngularJS in the controller to the view

I have a simple scope variable on my AngularJS Controller. It is assigned a specific endpoint value like this: $scope.isItAvailable = endpoint.IS_IT_AVAILABLE; How can I properly use it in my view (HTML) to conditionally show or hide an element using ng- ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

Angular2 only supports cross-origin requests for protocol schemes

I'm currently facing an issue while following the Angular Quickstart tutorial due to a CORS error. To resolve this, I made configurations in my Windows host file located under system32/drivers/etc/: 127.0.0.1 tour-of-heroes I also configured ...

The response from the XHR object is coming back as "Object Object

Recently, I've been faced with the challenge of working with an API that provides articles. Within the array returned by the API, there are attributes like author, title, and description. However, despite my efforts, each time I attempt to retrieve th ...

Check the browser's developer tools to access JavaScript files

I recently came across a server at example.noodles.com that is hosting a node.js application. I'm curious if there's a way to access the source files of this application using inspect element or some other method? Up to now, all I've been a ...

What is the best way to programmatically disable a button in JavaScript or jQuery when all the checkboxes in a grid are either disabled or unchecked?

In my grid, one column contains checkboxes. I need to implement a feature where a button is disabled if all the checkboxes are unticked. How can I achieve this using JavaScript or jQuery? .Aspx File <asp:TemplateField HeaderText="Cancel SO Line Item"& ...

Is XMLHttpRequest just sitting idle...?

As a newcomer to the world of javascript and AJAX, I've been stuck on a single problem for the past 8 hours. Despite my best efforts, I just can't seem to figure out what's going wrong. On my website, I have an image with an onclick event ca ...

transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows: def scoreValue = new HashMap<String,String>(); scoreValue.put("0","poor"); scoreValue.put("1","good"); ... retu ...

Transforming react.js into HTML and CSS programming languages

I have a small experiment I need help with. As I am not familiar with react.js, I would like to convert my main.jsx file into pure HTML/CSS/JS without using react. The issue I'm facing is how to handle form data submission to the server in vanilla HTM ...

updating page following redirection by the router

For my project which involves Laravel and Vue.js, I am looking to display a Gantt chart for each individual project. The goal is that when I click on the link of a specific project, it should redirect me to its respective Gantt chart. However, I am facin ...

Can you tell me which specific font Adobe Edge Code (Brackets) uses in its code editor?

Can someone please help me? I'm trying to identify the syntax highlighter being used in this code. Is it Prettify or something else? ...