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

Encountering issue with Konva/Vue-Konva: receiving a TypeError at client.js line 227 stating that Konva.Layer is not a

I am integrating Konva/Vue-Konva into my Nuxtjs project to create a drawing feature where users can freely draw rectangles on the canvas by clicking the Add Node button. However, I encountered an error: client.js:227 TypeError: Konva.Layer is not a constr ...

How to retrieve the current element in AngularJS version 1.x

I have done extensive research on how to get the current element in jQuery using $(this). However, I have not been able to find a similar method in AngularJS 1.x. Here is what I have tried: angular.element(this), but it does not work as expected. Below is ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

Using Vue.js to loop through data objects when a button is clicked

I'm currently working on building a quiz functionality using vue.js, but I've hit a roadblock in trying to make the "Next" button cycle through my data. The goal is to have the screen display the object containing the question and answers (e.g. q ...

`validate.js verifying the elements within an array`

One of the challenges I'm facing in my JavaScript project is dealing with objects that have two array properties included. As part of my development process, I've decided to utilize the resources provided by the validate.js library. To illustrat ...

Achieve the effect of making the Bootstrap JS Collapse text bold after it has been

Is there a way to make Bootstrap JS Collapse text Bold after it has been clicked on? <tr data-toggle="collapse" data-target="#demo8" class="accordion-toggle"> <td> <div class="fa ...

React Router: Dispatch not triggering when route changes

I have multiple paths that share the same controller: <Route component={Search} path='/accommodation(/:state)(/:region)(/:area)' /> and when the route changes, I trigger the api function within the component: componentWillReceiveProps = ...

Looking to display several charts on a single page with varying datasets?

I have successfully integrated a doughnut chart plugin into my website. However, I would like to display multiple charts on the same page with different data sets. Below is the code snippet for the current chart being used: This is the chart I am using & ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

Utilizing vuelidate in Vue 3: Overcoming Decorators Challenge in Composition API (`<script setup>`)

Currently working on upgrading from vue 2 to vue 3 and encountering an error with the @Component decorator: "Decorators are not valid here.ts(1206) (alias) Component(options: Vue.ComponentOptionsBase<Vue, any, any, any, any, any, any, any, string, ...

Searching for the index of a nested array in jQuery using JSON

I am currently working on developing an image uploader using Codeigniter3 along with jQuery and Ajax. Problem: I am facing difficulty in understanding how to locate the index of the array received from the ajax response shown below. Here is the data retu ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Updating a List Conditionally in React

Hello there! I am relatively new to the world of React and currently trying to grasp the concept of modifying elements within a list. Below, you'll find a straightforward example that illustrates my current dilemma. const numbers = [1, 2, 3, 4, 5]; / ...

The socket.io-client could not be located on the running Node.js server

Setting up a fresh installation of Node, Express, and Socket.io on a Linux environment using npm. When attempting to run a sample from the official socket.io source, I encountered an error stating that the 'socket.io-client' module was not found ...

Using JavaScript within HTML documents

Need help with inserting JavaScript code from Google: <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1362706866260-0'); }); </script> into existing JavaScript / HTML code: va ...

Ways to simulate a function that is a part of an internal object

Is there a way to mock a method from an object within my UnderTest class? When the Update method is triggered by an event from a child component, I need to mock the service.saveNewElement(data) method in order to test data in the then() block. <script ...

Using JavaScript, learn how to extract query parameters and encoded information from a URI

I am looking for a specific module in order to extract information from query parameters within a URL. The format includes 2 query parameters and an encoded piece of data. Do I need to use split functions or is there a more direct approach available? Sampl ...

Tips for incorporating material-ui icons into the column component of a data-grid component

I am currently working with the material-ui data-grid and I would like to display Edit icons from material-ui next to each row. Unfortunately, the data-grid does not provide any props specifically for this purpose. Below is the code snippet: import React ...

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...