Managing the creation of a fresh VueJs object with checkboxes enabled for CRUD operations

Hello fellow developers! I am currently working on a shop card project and I'm looking to add a new product to the collection of sale elements. Let's consider the JSON structure retrieved from the backend:

"products": [
    {
      "product_provider": "tupac shakur",
      "rate": 3,
      "product_image": [
        xxxxxxxxxxxxxxxxxxxxxx,xxxxxxxxxxxxxxxxxxx,xxxxxxxxxxxxxxxxxx
      ],
      "product_id": 1,
      "product_price": 153.4,
      "product_stock": 26,
      "product_description": "Wood cutter ",
      "product_name": "Chain Saw",
      "product_category": [
        {
          "categories_of_product": "Good"
        },
        {
          "categories_of_product": "Danger"
        },
        {
          "categories_of_product": "Homer"
        }
      ],
      "people_buying_this_product": "Jack Ripper"
    },
 ]

While working on adding products, I have created an HTML form that mimics the structure of the JSON object. This form submits data to Vuex to modify the variable containing all products for sale, including checkboxes for product categories (highlighted here as it poses an issue):

<v-layout v-for="(option,index) in ProductAdded.Categories" :key="index">
   <v-flex xs12>
     <div>
      <input name="id of product" label="id of product"type="checkbox" @click="option.selected = !option.selected"/>
      <label>{{ option.value }}</label>
     </div>
   </v-flex>
</v-layout>

The return data structure looked like this:

 data() {
    return {

      thisCurrent: null,

      ProductAdded: {
        description: "",
        upload_image3: "",
        upload_image2: "",
        upload_image1: "",
        unities: 0,
        price: 0,
        name: "",
        Categories: [
          { id: 1, value: "Miscellaneous", selected: true },
          { id: 2, value: "Homer", selected: true },
          { id: 3, value: "Electronic", selected: false },
          { id: 4, value: "Internet", selected: false },
          { id: 5, value: "Kids", selected: true },
          { id: 6, value: "Donas", selected: false },
          { id: 7, value: "Sports", selected: false },
          { id: 8, value: "Horror", selected: false}
        ]
      },

    };
  },

To handle the addition of products, I created a method to dispatch a Vuex action that pushes the new product to the existing sale items:

methods: {
    ...mapActions(["fetchAllProducts", "addProductSale"]),
    addProductOnSale(thisCurrent) {
      this.$store.dispatch("addProductSale", this.ProductAdded);
    },

  },

Subsequently, in Vuex, the action is called along with its mutations and getters:

VUEX

State:{
allProducts: {},
},

Mutations:{
settingProductSale(state,currentProduct){
      state.allProducts.products.push(currentProduct)
    }
},
getters:{
getAllProducts: state => state.allProducts,
}

The challenge lies within the `product_category` attribute in the action because aligning it with the JSON structure proves tricky, especially when dealing with checkbox selections. Any suggestions or ideas on how to approach this issue would be greatly appreciated. Thank you!

Answer №1

product_category: currentProduct.Categories.filter(selection => selection.selected)
?

perhaps I am mistaken and what you need is:

product_category: currentProduct.Categories.filter(selection => selection.selected).map(selection => {product_categories: selection.value})

?

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

Trouble with locating newly created folder in package.json script on Windows 10

I am facing an issue in my Angular application where I am trying to generate a dist folder with scripts inside it, while keeping index.html in the root folder. I have tried using some flag options to achieve this but seem to be stuck. I attempted to automa ...

Is it possible to utilize `ListBox` provided by `@headlessui/react` alongside Mobx?

Enhancing with ListBox: store/index.ts import { action, makeObservable, observable } from 'mobx' import type { IFrameItStore, TrafficSignal } from '@/types/index' export class FrameItStore implements IFrameItStore { trafficSignal: ...

A step-by-step guide on integrating HTML form input with an API object array

I'm looking to combine two code "snippets" but I'm not sure how to do it. One part of the code turns HTML form input into a JSON object. You can see the CodePen example here. What I want is when the "Add note" button is clicked, I want to grab ...

If the background color is blue, then element class will be added

Currently exploring the realm of JavaScript, I am tackling a challenge with adding a class to an element based on its background color. Specifically, I aim to add a class to elements with a background color set to rgb(32, 44, 62). However, my current imple ...

Using Three.js to render an octahedron shape

I attempted to create an Octahedron shape, but the final result did not meet my expectations. I am unsure of the reason behind this. Instead, I now plan to draw a Dodecahedron. Any suggestions or advice on how to achieve this? Click here to view the outcom ...

Leverage the specific child's package modules during the execution of the bundle

Project Set Up I have divided my project into 3 npm packages: root, client, and server. Each package contains the specific dependencies it requires; for example, root has build tools, client has react, and server has express. While I understand that this ...

Using the loop function within HTML in JavaScript with React

I'm trying to loop over my SliderComponent function with different inputs within the HTML to generate multiple components, but I can't seem to get it to work. I came across a solution online that involves building a string and returning it as HTM ...

Unlocking the full potential of Vue-FontAwesome: A step-by-step guide to importing both Free and Pro Icons without

I have possession of a FontAwesome Pro License and I am utilizing the Vue-FontAwesome Component. Whenever attempting to import icons from both the free and Pro repositories, an "Duplicate declaration error ..." occurs. Changing the declaration name result ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

Center JQuery within the current screen

My implementation of Jquery dialog is as follows: <body> <div id="comments_dialog"> Insert a comment <form> <input type="text" id="search" name="q"> </form> </div> .... </body> dialog = $( "#com ...

Even though I am utilizing the `.then()` method, my asynchronous function continues to return a status of

Here is my code attempting to retrieve response data. const fetchRobots = () => { axios.get("https://jsonplaceholder.typicode.com/users").then((response) => { return response.data; }); }; let robotsData = fetchRobots(); console.log(robots ...

Is there a newer alternative to the jQuery UI Draggable component available?

In search of draggable/sortable functionality for my .NET Razor Pages application. Came across the jQuery UI Draggable/Sortable component which I've used years ago with success. However, it's mentioned on the download page that the component is ...

Struggles encountered during the transition from Vuetify 1.5 to 2.1

I need some assistance with upgrading a vue/.net core project that I inherited from a former colleague who left. We are having difficulty successfully upgrading vuetify and despite researching extensively, I am unsure of the correct steps to take. Current ...

Using xignite api to retrieve stock data

I've been encountering difficulties trying to make this JavaScript script function properly. Every time I attempt to run it, I receive an error message stating: "XMLHttpRequest cannot load" "No 'Access-Control-Allow-Origin' header is presen ...

Ensure to add the name attribute when the checkbox is selected

Can anyone assist me with this issue? I am trying to create a form where, upon checking a checkbox, a name attribute should be added to the input field of the checkbox along with a number at the end. My current implementation is not working as expected. ...

Using Selenium webdriver to assign a JSON object to a paragraph element

What is the correct way to insert a JSON object into a p tag inside an iframe? I attempted the following approach but it displayed the text "[object Object]" rather than the actual content of the object... This is my implemented code: var arrJSON = [ ...

The AngularJS UI router is encountering an unexpected error: GET request not recognized

Need help with AngularJS Routing using UI-Router. My index.html file is attempting to load the partial productListView.html using app.js as javascript, but I'm encountering an error: "Unexpected request: GET productListView.html" in the console. Any a ...

Could offering a Promise as a module's export be considered a legitimate approach for asynchronous initialization in a Node.js environment?

I am in the process of developing modules that will load data once and create an interface for accessing that data. I am interested in implementing asynchronous loading of the data, especially since my application already utilizes promises. Is it considere ...

Are there any alternative approaches to handling frequent database updates in web development aside from using Websockets/AJAX for coding?

Currently, I'm in the process of developing an HTML and Javascript game and looking to implement a feature that displays the player's gold balance on the screen. The goal is to have this balance decrement by 1 every time the player clicks on a sp ...