"Encountering an error in Vue.js when trying to dynamically access nested arrays: push function not

My goal is to have two buttons displayed when a user uploads data: one for old products and one for new products. When the user clicks on either button, the corresponding products will be uploaded as 'old_product' or 'new_product'. However, I encountered an error when attempting this:

_this.product[value].push is not a function

Below is the code snippet:

<template>
  <div>
    <input type="file" class="product_upload" id="product_upload" @change="previewFiles">

    <button type="button" class="btn btn-primary" @click=uploadProduct('new_product')>New Product</button>
    <button type="button" class="btn btn-primary" @click=uploadProduct('old_product')>Old Product</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        product: {
          old_product: [],
          new_product: []
        }
      }
    },
    methods: {
      previewFiles(event){
        return event.target.files;
      },
      uploadProduct(value){
        let files = this.previewFiles;
        
        this.product[value].push(files);
      }
    }
  }
</script>

Answer №1

Here is the code snippet for your reference:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',

  data() {
    return {
      files: [],
      product: {
        old_product: [],
        new_product: []
      }
    }
  },
  methods: {
    previewFiles(event) {
      this.files = event.target.files;
    },
    uploadProduct(value) {


      this.product[value].push(this.files);
    }
  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">

  <div>
    <input type="file" class="product_upload" id="product_upload" @change="previewFiles"/>

    <button type="button" class="btn btn-primary" @click=uploadProduct('new_product')>New Product</button>
    <button type="button" class="btn btn-primary" @click=uploadProduct('old_product')>Old Product</button>

    <pre>
  {{product}}
  </pre>
  </div>


</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

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

How can I dynamically assign ngModel in AngularJS?

I've created a directive with an isolate scope that maps a list of objects to inputs for modifying a specific property. However, I now aim to make this component more universal by allowing it to bind to deeply nested properties within each object. Fo ...

Steps to display a list of errors received from Express using Vue.js following a post request

My goal is to develop a simple register/sign up web application using Express, Vue.js, and MongoDB. I have implemented backend validation checks such as ensuring all fields are filled out and checking if the passwords match. Any errors encountered during ...

Can Pinia support using non-root elements as reactive objects?

If you want to understand the basics of reactive properties, check out Pinia's tutorial at . The tutorial focuses on creating a counter that increments without the need for getters and actions. But here's a question: Can you achieve the same sim ...

What steps should I take to correct the color selection of a button that has been pressed down

Here is the code snippet that I am currently working with: HTTP: <label class="instructions" for="hidden_x"> Insert X: </label> <button type="button" class="button" name="button_x" value="1" id="x_1" onclick="document.getElementById(' ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Retrieve a specific value from a JavaScript object

Utilizing the npm package app-store-scraper, I am extracting the app IDs of 1000 apps from the App Store. My objective is to retrieve the "id" field from each JavaScript object and save it in a .csv file. How can I accomplish this task? Below is the code ...

Resolving the issue of multiple instances of React within a single application

I'm currently working on a React module in my local environment. To link the module, I am using npm link. Although the module is being imported successfully, the hooks inside the module are failing with the following error message: Invalid hook call ...

Utilizing Javascript Conditional for Substitution

Currently, I have a JavaScript function that replaces all links with registration messages: <script> function replaceLinks() { var links = document.querySelectorAll('.restore a:link'); for (var i = 0; i < links.length; i++) { ...

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

the div background is limited to the exact size of the text, not filling the entire

Currently, as I work on my web page using react.js, I'm facing the challenge of implementing a full-size background. Despite my efforts, the background only occupies the size of the text within the div. Here is the snippet of code I am working with: a ...

Retrieving the selected option from a dropdown list in VueJS

I have been struggling to store the selected value from a dropdown list as a data object in Vue. Despite my attempts, I am unable to successfully save the value in the Vue data object. I have experimented with using onchange and v-model.lazy, but I am unsu ...

When I try to upload an image onto my website, the layout of my text gets disrupted

There seems to be quite a gap between the welcoming message and the main body text. Significant spacing noticed between Title and body ...

How to send arrays through JSON?

I have some PHP code: $ids = array(1,2,3); $names = array("cat","elephant","cow"); $originalSettings = array ('ids'=>$ids,'names'=>$names); $jsonSettings = json_encode($originalSettings); echo $jsonSettings; Here ...

How can VueJS cycle through the arrays within an object?

Is there a way to efficiently iterate through arrays within an object like in this example? I have a simple code snippet that currently outputs indexes in order, but I'm looking to access the values of the array instead. <template> <div&g ...

Postgres.js Date Range query failing to fetch any results

Recently, I have been utilizing the Postgres.js npm module to interact with a PostgreSQL database Below is the code snippet for executing the query: let startDate = '2020-01-28 08:39:00'; let endDate = '2020-01-28 08:39:59'; let table ...

What are the signs of a syntax error in a jQuery event like the one shown below?

One of my forms has an ID attribute of id ='login-form' $('#login-form').submit(function(evt) { $('#login-button').addClass('disabled').val('Please wait...'); evt.preventDefault(); var postData = ...

Replace minor components (SVG) within the primary SVG illustration

I'm interested in transforming SVG elements into the main SVG element. For example, let's say the black square represents the main SVG element. I want to change elements 1, 2, and 3 to different SVG elements using JavaScript code. However, I am u ...

Selecting random numbers in React.js

I am working on creating a Netflix Clone and I want to change the banner image every time the page refreshes. I have integrated movie details from TMDb and have an array containing these details. My goal is to select a random number between 0 and 19 and us ...

Mysterious Loop in JavaScript Unfolding with Three.Js

In order to expand my knowledge of Angular and Three.Js, I am currently working on a prototype SPA that showcases different 3D elements rotating. There are several Angular templates accessible through a navigation menu, each displaying unique rotating elem ...