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

Switch out the vuetify simple-table for the data-table component

I need help transitioning a basic table in Vuetify with no headers and one column to a v-data-table. How can I make this change? <v-simple-table> <thead /> <tbody> <tr v-for="item in categories" ...

What could be causing the sporadic functionality of my jQuery image resizing code?

Seeking help for an issue I am facing with my jQuery code. I have been trying to scale a group of images proportionally within an image carousel using jCarousel Lite plugin. However, the resizing code seems to work randomly and I can't figure out why. ...

What could be the reason behind encountering an NaN error while using these particular functions?

I recently delved into the world of JavaScript, starting my learning journey about two months ago. While going through a few tutorials, I stumbled upon an intriguing project idea. However, I've hit a roadblock that's impeding my progress. Every t ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

"An error message stating 'Express: The body is not defined when

I'm encountering an issue while trying to extract data from a post request using express. Despite creating the request in Postman, the req.body appears empty (console.log displays 'req {}'). I have attempted various solutions and consulted s ...

Is there a way to access the active request being processed in a node.js environment?

I am currently working with express.js and I have a requirement to log certain request data whenever someone attempts to log a message. To accomplish this, I aim to create a helper function as follows: function logMessage(level, message){ winston.log(le ...

Transferring callback variables from an Express GET request to a forked process in Node.js

I encountered an issue while trying to transfer the callback variables from app.get() to a forked process. The error message I received was: TypeError: Converting circular structure to JSON The primary goal behind this endeavor is to enable a main node w ...

Validation of the existence of a MongoDB user

I'm currently working on implementing a sign-up form using Mongo, Node.js, and Express.js. I've managed to successfully insert a document into the users collection for a new user. However, I now need to set up validation to check if a user alread ...

What is the best way to incorporate a button that can toggle the visibility of the sidebar on my post page?

Check out this post of mine I noticed a button on someone's page that could hide their sidebar and expand it again when clicked. How can I implement this feature? Is it a simple task? ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

What is the best way to retrieve ember model relation properties within routes and controllers?

Currently using ember 2.7.0, I am facing an issue while setting up my ember app with a currentUser.organization derived from the authenticated token. Although I can successfully resolve the currentUser, I am encountering difficulties in resolving the prope ...

``The problem of cross-origin resource sharing (CORS)

Encountering a CORS error when sending the request, although it works fine in Postman Error Message: The fetch request to (cloud function url) from my web app origin is being blocked by CORS policy: No 'Access-Control-Allow-Origin' header is p ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Is there a way in Angular Material to consistently display both the step values and a personalized description for each step?

Is there a way to display both numerical step values and corresponding custom text in Angular Material? I prefer having the number at the top and the descriptive text at the bottom. Check out this image for reference: https://i.stack.imgur.com/LGMIO.png ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

What is the process of emphasizing a WebElement in WebdriverIO?

Is there a way to highlight web elements that need to be interacted with or asserted in webdriverIO? Or is there a JavaScript code similar to the javascript executor in Selenium that can be used for this purpose? ...

Issues within jQuery internal workings, implementing improved exception handling for fn.bind/fn.apply on draggable elements

I've been experimenting with wrapping JavaScript try/catch blocks as demonstrated on this link. It functions properly, essentially encapsulating code in a try/catch block to handle errors like so: $.handleErrors(function(e){ console.log("an erro ...

Combining JWT authentication with access control lists: a comprehensive guide

I have successfully integrated passport with a JWT strategy, and it is functioning well. My jwt-protected routes are structured like this... app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thing ...

Prevent Dehydration issue while using context values in Next Js

Every time I log in with a user, update a context value, and re-render some components, I keep encountering a Hydration error in Next Js. The issue seems to be specifically with my NavBar component which is rendered using react-bootstrap. The code snippet ...