"Creating a dynamic Vue array using computed property from the provided dataset

Let's consider a scenario where data is retrieved from a store:

let itemsData=[
  {id:1,data:[...]},
  {id:2,data:[...]},
  {id:3,data:[...]}
]

The goal here is to create another array, itemsSelected, that looks like this:

let itemsSelected=[
  {id:1,selected:false},
  {id:2,selected:false},
  {id:3,selected:false}
]

This new array, itemsSelected, needs to be easily accessible to determine the state of various components in the template. For instance:

<div v-for="item in itemsSelected" :key="item.id" :class="item.selected?'selected':''"></div>

A computed property might seem like a solution at first, but there's a need to dynamically update the selected value for items in itemsSelected. Additionally, we want the array to reflect changes in itemsData, adding or removing items accordingly. How can these goals be achieved simultaneously?

Answer №1

One way to keep itemSelected in sync with itemsData is by using a watcher mechanism. In the example below, we leverage Array.prototype.reduce along with Vue's reactivity features:

import { watchEffect, ref, reactive } from 'vue'

let itemsData = reactive([
  { id: 1, data: [newData()] },
  { id: 2, data: [newData()] },
  { id: 3, data: [newData()] },
])

let itemsSelected = ref({})

watchEffect(() => {
  const selections = itemsSelected.value
  itemsSelected.value = itemsData.reduce((prev, curr) => {
    prev[curr.id] = {
      ...curr,
      selected: selections[curr.id]?.selected ?? false,
    }
    return prev
  }, {})
})

With this setup, you can freely modify the selected properties within itemsSelected while keeping itemsData unaffected.

Check out this demo for a live example.

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

Why is the output showing as abnormal?

There are occasions when I am unable to successfully execute this script! var b = [9,8,7,6,5,4,3,2,1]; var a = (function(){ var W = []; for(var k in b){ W[W.length] = { index : k, fx : function(){ console.log(k); ...

I am attempting to gather outcomes from two separate arrays

I have a challenge of filtering the first array based on the text in the second array. I am trying to figure out how to update the count filter in the first array using values from the second array. First Array: var firstArray =[{text:"India",co ...

Sending Data Through Button from navBar in React-Native-Router-Flux

I have been working on a project that utilizes `react-native-router-flux` and I am facing a challenge in passing an object through `props`. Typically, I would use `Actions.someKey({ someProp: object })` for navigation. However, in this case, I need to navi ...

The CustomValidator ClientValidationFunction will only activate on the second or subsequent submission if CheckBoxList is checked

I am encountering an issue with a user control that is dynamically added to pages on DNN. The user control is built on a customized version of CheckBoxList and includes a CustomValidator with ClientValidationFunction set to a javascript function. It works ...

Troubleshooting the issue of the background of element A not changing when hovering over element B, despite mouseleave not

Currently, I am attempting to modify the background of element A when mouseover event occurs on element B, and then revert it back to its original state upon mouseleave. It's worth noting that B is nested within A. Strangely, while the background colo ...

Prevent the onClick event in the parent container div from triggering when clicking on a child element

Having trouble with event bubbling and onClick functions within a card element. The card has a heart icon that triggers an onClick function to unlike the card, but it also triggers the onClick function for the entire card which leads to a different page wi ...

Determining the measurements of an svg path without relying on the bounding box

Is there a way to retrieve the dimensions of an svg path and showcase it within a div without relying on the bounding box method? I've noticed that the bounding box can be buggy in Webkit especially with bezier curves. Just so you know, I am currently ...

Shutting down a filtered v-treeview node becomes sluggish when operating with a large number of items

My v-treeview has a node with approximately 2000 children, and I am in need of applying a filter to it. However, the current issue is that opening the node takes around 3 seconds, while closing it takes about 15 seconds, which is completely unacceptable. ...

Bootstrap modal with sticky-top class displays abnormal margin and padding upon being shown

Whenever I launch a bootstrap modal, I notice unexpected side padding or margin appearing on certain HTML elements. For instance: Before displaying the modal: <div id="fixedMenu" class="d-none container-fluid menu sticky-top px-0" s ...

Using AngularJS API within a standalone function: Tips and tricks

I'm diving into the world of AngularJS and I want to make an HTTP GET request to a distant server without messing up my current view code. After some research, I discovered a way to execute a function right after the HTML is loaded by using a standalo ...

Modifying element size using jQuery causes issues with maintaining a 100% height

I am facing an issue with a sidebar that is styled using the following css properties: background:#164272; position:absolute; left:0px; top:70px; width:250px; height:100%; When I use jQuery to display a table that is initially hidden and on ...

Is there a way to save a collection of audio samples as a wav file using Node.js?

In my JavaScript code, I am developing an oscillator that generates a sweep (chirp) between different sine wave frequencies. To test this functionality, I would like to save the samples (which are in floating point format) to a WAV file. Can anyone provi ...

jquery: conditions fail to execute

Looking at the code snippet provided, it appears quite straightforward. The intention is to display an alert labeled "Trigger 2" if the variable "ret" returns a value of "fail". However, there seems to be a glitch with the IF statement causing it to trigge ...

Utilizing the map function to modify the attributes of objects within an array

I have a data structure with unique IDs and corresponding status keys. My goal is to count how many times each status repeats itself. Here's an example of my data structure: const items = { id: 2, status_a: 1, status_b: 1, status_c: 3 }; Below is the ...

Typescript is unable to comprehend that the initial item in an array of strings is considered to be a string

Here are the functions I am working with: const transitionGroup = ( propertyName: string, durationMultiple = 1, timingFunction = 'linear', delayMultiple = 0, ): string => { // ...more logic here return [propertyName, duration, tim ...

Changing the shape of a background using CSS when hovering

My Bootstrap navigation has a unique setup, as shown below. I've observed that many users tend to only interact with the headings and ignore the submenus where the actual products are located. To address this issue, I want to change the design of th ...

Encountering CORS issue while trying to connect frontend with microservice API in a production environment

I am encountering CORS issues in my production environment with a microservice-based application that functions smoothly in development. Whenever my frontend attempts to send a request to the ApiGateway, I encounter the following error: Access to XMLHttpRe ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

I am feeling quite lost in trying to figure out how to create a voice mute command using Discord

I've been searching for information on how to create a command that mutes only one specific person I tag in chat, but I'm having trouble finding any guidance on it. As someone new to discord and node js, I could really use some assistance. Mute ...

Tips for Creating and Verifying JWE in Node.js

I attempted to use the following code in order to create an RSA-OAEP and A128GCM JWE generator and validator. It successfully encrypts claims and generates the JWE, then decrypts it and provides me with the original claims when running on node.js. However, ...