Combining arrays of objects in VueJS

I am working with 2 components:

  1. parent component (using vue-bootstrap modal with a vue-bootstrap table)
  2. child component (utilizing vue-bootstrap modal with a form)

Issue: When I submit the form in the child component, it successfully adds the object to the parent table array. However, the problem arises when I reset the form as it also resets the object in the table array, causing confusion. I have tried both push and concat methods without success.

Parent variable:

MA02_E_tb // table array [{descr_forn: '',fornitore:'',n_oda:''},{descr_forn: '',fornitore:'',n_oda:''}]      
 data() {
      return {
        form: {
          descr_forn: 'prova',
          fornitore:'prova',
          n_oda:'prova',
      }
    },
  methods: {
      resetModal() {
        this.form.descr_forn = '',
        this.form.fornitore = '',
        this.form.n_oda = '',
      },
      onSubmit: function(evt) {
        evt.preventDefault()
        this.$parent.MA02_E_tb = this.$parent.MA02_E_tb.concat(this.form)
      },

Result:

MA02_E_tb = [{descr_forn: 'prova',fornitore:'prova',n_oda:'prova'}]

Upon reopening the child modal and resetting the form object with the resetModal method, the result changes to:

MA02_E_tb = [{descr_forn: '',fornitore:'',n_oda:''}]
form = [{descr_forn: '',fornitore:'',n_oda:''}]

The confusing part is why does it reset MA02_E_tb even though it's a different variable?

Answer №1

It's highly discouraged to use $parent in this manner. Instead, consider emitting an event. However, the issue lies elsewhere.

The root cause is passing an object by reference. Any changes made to the object will reflect in all instances of it. Regardless of how you access it, it remains the same object.

If the object is flat, you can create a shallow copy using the spread operator, ...:

this.$parent.MA02_E_tb = this.$parent.MA02_E_tb.concat({...this.form})

This will generate a new object with identical properties as this.form. Note that this is only a shallow copy. If this.form contains nested reference types (e.g. objects, arrays), those should be copied individually as well.

For an event-driven approach:

this.$emit('submit', {...this.form})

You must then have a corresponding @submit listener in the parent template to update the array. The concept here is that data modifications should only be allowed by the data owner, which in this case, is the parent array.

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

Guide to direct express.js requests straight to 404 page

I need guidance on how to direct a request to a specific route in express.js directly to a 404 error page if the user is not authenticated. Currently, my middleware includes the following code: exports.isAuthenticated = function (req, res, next) { if ( ...

Dropdown selection for countries that dynamically updates region choices

Looking to implement some JavaScript, preferably using jQuery, to create a cascading dropdown menu. Initially displaying a list of countries and upon selection, the corresponding regions for that country will be displayed in another dropdown. I assume an ...

Error encountered during AJAX POST request: NETWORK_ERR code XMLHttpRequest Exception 101 was raised while using an Android device

Here is the ajax post code that I am using: $.ajax({ type: "POST", url: "http://sampleurl", data: { 'email':$('#email').val(), 'password':$('#password').val(), }, cache: false, ...

Sending a request from JavaScript to C# methods using AJAX, with no expected response, within an ASP.NET MVC framework

Setting up the Environment: <package id="jQuery" version="3.2.1" targetFramework="net45" /> <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" /> Recently, I encountered an issue while trying to send a request from one ...

Exploring Material UI: Understanding the contrast in functionalities between incorporating the Icon component and the Material Icons node

I am looking to incorporate Material Icons into my application. I have come across two methods provided by Material UI for adding the same icon to my site: Using the <Icon /> component, which is part of the @material-ui/core package: <!-- Add t ...

Adjusting the speed of Flexslider with mousewheel control

I am looking to implement flexslider with mousewheel functionality. Here is an example of how I want it to work: $('#slider').flexslider({ animation: "slide", mousewheel: true, direction: "vertical", ...

Converting an object of objects into an associative array using Javascript and JSON

Using AngularJS, I am sending this data to my API : $http.post('/api/test', { credits: { value:"100", action:"test" } }); Upon receiving the data in my nodeJS (+Express) backend, it appears as follows : https://i.stack.imgur.com/NurHp.png Why ...

Troubleshooting MaterialUI Datatable in Reactjs: How to Fix the Refresh Issue

Currently, I am facing an issue with rendering a DataTable component. The problem is that when I click on the "Users" button, it should display a table of Users, and when I click on the "Devices" button, it should show a table of Devices. But inexplicably, ...

JS : Removing duplicate elements from an array and replacing them with updated values

I have an array that looks like this: let arr = ['11','44','66','88','77','00','66','11','66'] Within this array, there are duplicate elements: '11' at po ...

Unable to refresh the view from the controller once the promise has been resolved

On my webpage, I want to display a dynamic list of items that updates whenever the page is refreshed. To achieve this, I am using Parse to store and retrieve my items using promises. Here's a simplified example of how it works: When the index.html pa ...

Is there a way for me to access the information within these curly brackets [[]}?

I'm facing a challenge where I need to extract the ID from an API response that is formatted in a way unfamiliar to me. As a result, I'm unsure of how to retrieve the ID data from this response. (This is my initial query, so if it's unclear ...

leveraging array elements in the data and label properties of a chart.js chart

I would like to assign the values of an array to the data and label fields within a chart.js dataset. Below is the code executed upon successfully fetching JSON data using an AJAX call. The fetched JSON data is then stored in an array. Data = jQuery.pars ...

Removing outline from a Material UI button can be done using a breakpoint

Is there a way to remove the outlined variant for small, medium, and down breakpoints? I have attempted the following approach: const selectedVariant = theme.breakpoints.down('md') ? '' : 'outlined'; <Button name="buy ...

What steps can be taken to send the user to the login page after their session token has expired

Currently, I am using a Marionette + Node application. I have noticed that when the token expires, the application does not respond and the user is not redirected to the LogIn page. My question is, how can I set up a listener to check the session token s ...

Are you experiencing issues with the map displaying inaccurate latitude and longitude when clicking on a specific point?

I've successfully created a simple polyline on Google Maps and attached a click event listener to it. However, I'm encountering an issue where clicking on the line provides me with latitude and longitude coordinates that point to Canada, even th ...

Optimal method for file uploading with Node.js

How can I effectively manage file uploads in node js? I would like users to be able to upload profile images with the following specifications: -Validated size of at least 200 * 200 -Accepted file formats are png, jpg, jpeg, or gif -Additional functi ...

How can I generate rotating images using jQuery or JavaScript similar to the one shown here?

http://www.example.com/ On a website similar to example.com, I noticed that when hovering over one of the topics listed, the image rotates. I am interested in creating this interactive effect using either jQuery or JavaScript. Is there a method to access ...

How can one generate an HTML element using a DOM "element"?

When extracting an element from an HTML page, one can utilize a DOM method like .getElementById(). This method provides a JavaScript object containing a comprehensive list of the element's properties. An example of this can be seen on a MDN documentat ...

Internet Explorer 11 XHR Troubles

Our company has successfully developed a JavaScript video player that can be embedded on various websites using a script tag. As part of the bootstrapping process, we utilize XMLHttpRequest to fetch resources from our server. This creates cross-origin requ ...

Guide on Developing a JavaScript Library

After creating several JavaScript functions, I noticed that I tend to use them across multiple projects. This prompted me to take things a step further and develop a small JavaScript Library specifically for my coding needs. Similar to popular libraries l ...