What is the best way to utilize v-model to set values within a 2D array?

I would like to populate a 2D array with values using v-model.

Here is an example of my array containing objects:

[
  {
    first_attribute_value: 'red',
    second_attribute_value: 'medium',
    third_attribute_value: 'cotton',
    quantity: [
      { location_id: 32, quantity: '' },
      { location_id: 31, quantity: '' },
      { location_id: 30, quantity: '' },
      { location_id: 1, quantity: '' },
    ],
  },
  {
    first_attribute_value: 'red',
    second_attribute_value: 'medium',
    third_attribute_value: 'leather',
    quantity: [
      { location_id: 32, quantity: '' },
      { location_id: 31, quantity: '' },
      { location_id: 30, quantity: '' },
      { location_id: 1, quantity: '' },
    ],
  },
],

Here is the function that returns the testvar array:

 setVariancesJSON(){
           this.firstattrs.forEach(first=>{
             if(this.secondattrs.length && this.thirdattrs.length){
            this.secondattrs.forEach(second=>{
            this.thirdattrs.forEach(third=>{
            this.testvar.push({
            first_attribute: this.attrnames[0],
            first_attribute_value: first,
            second_attribute: this.attrnames[1],
            second_attribute_value: second,
            third_attribute: this.attrnames[2],
            third_attribute_value: third,
            quantity:this.freeProductQuantity
                     })
                 })
             })
             }
             else if(this.secondattrs.length && !this.thirdattrs.length){
                 this.secondattrs.forEach(second=>{
                     this.testvar.push({
            first_attribute: this.attrnames[0],
            first_attribute_value: first,
            second_attribute: this.attrnames[1],
            second_attribute_value: second,
            third_attribute: null,
            third_attribute_value:null,
            quantity:this.freeProductQuantity
                     })
                 })
             }
             else{
                   this.testvar.push({
            first_attribute: this.attrnames[0],
            first_attribute_value: first,
            second_attribute:null,
            second_attribute_value: null,
            third_attribute: null,
            third_attribute_value:null,
            quantity:this.freeProductQuantity
                     })
             }

         })
     }

I attempted to assign values to the quantity attribute within each quantity array

This was my approach:

<tr v-for="(attr,index) in testvar " :key="index">
  <td class="col-2 text-center" v-for="(warehouse,index2) in warehouses" :key="index2">
    <input v-model="testvar[index].quantity[index2].quantity">
  </td>
</tr>

However, all input fields display the same value for each column instead of unique values. It seems to always read "index" with the same value during each iteration.

Answer №1

Kindly review the code snippet below (index2 has been corrected):

new Vue({
  el: '#demo',
  data() {
    return {
      testvar: [{"first_attribute_value": "red", "second_attribute_value": "meduim", "third_attribute_value": "cotton", "quantity": [{"location_id": 32, "quantity": "5" }, {"location_id": 31, "quantity": ""}, {"location_id": 30, "quantity": ""}, {"location_id": 1, "quantity": ""}]}, {"first_attribute_value": "red", "second_attribute_value": "meduim", "third_attribute_value": "leather", "quantity": [{"location_id": 32, "quantity": ""}, {"location_id": 31, "quantity": "7"}, {"location_id": 30, "quantity": ""}, {"location_id": 1, "quantity": ""}]}]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <table>
    <tr v-for="(attr, index) in testvar " :key="index"> 
      <td class="col-2 text-center" v-for="(warehouse, index2) in attr.quantity" :key="index2"> 
        {{ warehouse.location_id }}
        <input v-model="testvar[index].quantity[index2].quantity"> 
      </td> 
    </tr>
  </table>
  <p>{{ testvar }}</p>
</div>

Answer №2

Uncertain about the concept of warehouses. Consider iterating through the quantity array in each object of testvar for a second time.

View Demo :

const application = new Vue({
  el: '#application',
  data() {
    return {
      testVariable: []
    }
  },
  methods: {
    fetchData() {
      this.testVar.push({
          firstAttributeValue: 'red',
          secondAttributeValue: 'medium',
          thirdAttributeValue: 'cotton',
          quantity: [
            { locationId: 32, quantity: '' },
            { locationId: 31, quantity: '' },
            { locationId: 30, quantity: '' },
            { locationId: 1, quantity: '' },
          ],
        },
        {
          firstAttributeValue: 'red',
          secondAttributeValue: 'medium',
          thirdAttributeValue: 'leather',
          quantity: [
            { locationId: 32, quantity: '' },
            { locationId: 31, quantity: '' },
            { locationId: 30, quantity: '' },
            { locationId: 1, quantity: '' },
          ],
        }) 
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="application">
  <button @click="fetchData()">Fetch Data</button>
  <table>
    <tr v-for="(attr,index) in testVar" :key="index">
      <td class="col-2 text-center" v-for="(warehouse,index2) in attr.quantity" :key="index2">
        <input v-model="testVar[index].quantity[index2].quantity">
      </td>
    </tr>
  </table>
</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

Problem with the require systeminformation module in NW.js (node-webkit) and Vue.js

Seeking help with integrating the systeminformation module into a project that uses NW.js and Vue.js. This module cannot be included in Vue.js due to its restriction of only working on a server-side, as outlined in the documentation's core concept sec ...

Updating the value within the render() function in React - a guide

I am struggling to display the data retrieved from the websocket in my application. The render function is not updating even after receiving data from the socket. I tried to update the state with this.state when new data arrives from the websocket, but it ...

Modifying JavaScript prototypes on the fly can lead to troublesome issues

My curiosity has been piqued by the concept of dynamically changing a constructor's prototype in JavaScript, leading me to the findings above. It appears that an already constructed instance does not inherit the properties of the newly changed protot ...

Interactive features causing compatibility problems with Next.js 14 server communication, including API calls and data transmission to components

Currently, I am working with the architecture of the Next.js App Router and facing a challenge with my post page. This page fetches data from an API and passes it to a component. So far, I've managed simple interactions like style changes upon clickin ...

Text positioned next to a line in three.js

Within a scene constructed from JSON data, I have a tube geometry that requires a line marker at each segment. To achieve this, I am using the centroid of a face as the starting point and adding 10 to each coordinate of the centroid for the end point of th ...

Unable to set a JSON data as a value for a JavaScript variable

I am currently developing a YT mp3 downloader using the API provided by youtubeinmp3. I have been successful in obtaining the download link in JSON format. https://i.stack.imgur.com/3mxF2.png To assign the value of "link" from the JSON to a JavaScript va ...

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

I need to update my database by sending requests to my API, as the changes are not being reflected in the current database state. I am eager to see the

Struggling to grasp the concept of making requests to an API that uses express for CRUD operations. In the code snippet below, .get(/bears) displays a form and in app.post('/bears'), I'm using the 'request' module to send a request ...

Restricting the select drop-down menu in VueJS to only show options when there are two or more available

I am working on implementing select drop-downs that load data using Axios calls. My goal is to disable the drop-downs (grey them out) if there are less than 2 options available. I have successfully disabled a submit button as a test, but I am struggling ...

Client is currently experiencing difficulties receiving text content from the server

When working on a CRUD operation involving Indian language messages, I encountered an issue. While I was able to successfully create and save the message, upon attempting to read it back, all I received was "???". It seems like there is some sort of encodi ...

java and selenium for element with div that scrolls

Looking for a way to scroll within an inner window (i.e. div)? Check out this helpful website: How to scroll to an element inside a div? I came across some Javascript solutions, but I'm struggling with passing values back to Java while using the exec ...

Having trouble adding a root view in React Native

Recently I attempted to incorporate 'react-native-popup' into my project, only to encounter a frustrating error message displayed on a red screen when rendering the popup. Oddly enough, upon reloading the app, the error transforms into a warning ...

When a user clicks, use Jquery to display the sidebar and hide it when

Hey, I could really use some help with this script. I've managed to get the panel to show with a mouse click, but I want it to close when the mouse leaves the panel. Here's a sample: http://jsfiddle.net/jikey/w9s7pt25/ $(function(){ $(' ...

Update the division by clicking the button with a randomly generated JavaScript string element

Trying to solve a unique problem here as none of the proposed solutions on similar questions have worked for me. Apologies if I'm missing something, I'm new at this. The issue is with loading an empty div on my page using javascript and strings ...

How to properly handle sending an empty post request in Angular 2

My current issue revolves around attempting to send data from my application to the server using a POST request, however, the server seems to be receiving empty POST data. This is the function responsible for sending the data: private headers = new Heade ...

Proceed with downloading the file only when a checkbox has been ticked off and the form has been

Is there a way to make a PDF download only when a user checks a checkbox and submits the form, rather than just checking the checkbox and hitting submit? I am limited to using Jquery or plain javascript and do not have access to backend files. The checkbox ...

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

Expanding the jquery accordion as the page loads

Upon loading the page, the jQuery accordion should automatically open. Once the page is fully loaded, the accordion should compact itself. jQuery().ready(function(){ jQuery('#portslid').accordion({ collapsible: true, autoheight: false, alwaysO ...

Adjust dimensions of an image retrieved from a URL

Is there a way to adjust the size of the image displayed here?: var picture = new Image(); picture.src = 'http://www.example.com/images/logo.png'; picture.width = 200; //trying to change the width of the image $('canvas').css({ ...

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...