Vue modifies the array in the data after creating a duplicate of it

Here is the Vue code snippet I'm working with:

export default {
 name: 'Test',
  data() {
    return {
      test1: ['1', '2', '3'],
      test2: [{
        name: 'Hello'
      }, {
        name: 'Number two'
      }, {
        name: 'What ever'
      }], 
     };
  },
 created() {    
    const first = [...this.test1];
    first.forEach((elm, index) =>  first[index] = 'New');
    console.log('first: ', first);
    console.log('test1 in data', this.test1);

    const second = [...this.test2];
    second.forEach(elm => elm.name = 'New');
    console.log('second: ', second);
    console.log('test2 in data', this.test2);
  },
}

After modifying each element of the 'first' array (a copy without reference to 'test1'), all items are updated to 'new'. However, the original value of this.test1 remains unchanged.

A similar process was done for test2. The values were copied and changed to 'New'. Surprisingly, the values in the 'test2' data array have also been updated to 'New' in every item.

This behavior has caught me off guard. Any insights into why this is happening?

Answer №1

Applying spread syntax allows you to generate a shallow duplicate. When dealing with arrays containing primitive data types like numbers or strings, the original array remains unchanged. This is demonstrated in the scenario of test1. In this case, a new array is only produced. Modifying the new array through operations such as push or pop does not impact the initial array. However, objects within the arrays still reference the same memory location. Consequently, alterations made to these objects will reflect in the original array as well.

To produce copies of individual objects using spread syntax, you can employ:

const second = this.test2.map(o => ({...o}))

An alternative approach involves utilizing JSON.parse and JSON.stringify. Yet, if the objects contain any function properties, they will be eliminated:

const second = JSON.parse(JSON.stringify(this.test2))

Answer №2

The rationale behind this behavior is due to the presence of a Vue data values array. When cloning the array, the getters and setters associated with each value are also copied, maintaining a reference to the original array. To eliminate these getters and setters, it is advisable to follow the suggestion provided by d-h-e.

Another approach you can take is as follows:

const second = this.test2.map(() => { name: 'New' } );
console.log('second: ', second);
console.log('test2 in data', this.test2);

Answer №3

Give it a shot:

let newArr = JSON.parse(JSON.stringify(this.arr));

If you have complex arrays, using the spread operator or Array.from won't suffice. For deep copying, rely on the combination of JSON.parse and JSON.stringify methods.

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

Sending JSON array from PHP to jQuery AJAX

Currently, I am working on an experimental project where I need to search for a product in a MySQL database using the product name and retrieve the price in the 'price input' field and sell price in the 'sellprice input' field. You can ...

Tips for managing the onloadedmetadata event

If a video file cannot be played by the browser due to format or codec issues, I want to notify the user about it. When the browser is unable to play a video (because of unsupported format or codec), the onloadedmetadata event does not occur. I have some ...

Exhilarating Javascript document with fresh lines and line breaks

In my current project, I am dynamically generating a JavaScript page using PHP and .htaccess to convert .php files into .js files. Everything is functioning properly, except for the output of the JavaScript code. For example: $data = array('one&apo ...

Can one manipulate the simulation to make isTrusted=true a reality?

Is there a way to simulate an isTrusted=true in touchStart event triggering? Are there any libraries or workarounds that can make this achievable? When I run the touchStart event programmatically versus physically triggering it, the output differs. Below ...

Sorting an array of numbers using Javascript

Does anyone know how to properly sort an array in JavaScript? By default, the sort method doesn't work efficiently with numbers. For example: a = [1, 23, 100, 3] a.sort() The sorted values of 'a' end up being: [1, 100, 23, 3] If you hav ...

Validation of dynamically generated name fields using radio button group

CODE: html <form id="myform" type="post"> <fieldset id="myid1"> <input id="entries_8490_burn_id_1" name="entries[8490][burn_id]" value="1" type="radio"/> <input id="entries_8490_burn_id_2" name="entries[8490][burn ...

Converting a Powershell array into an HTML format

I have three arrays that I need to display on an HTML page: foreach($item in $array1){ // write array data to HTML } foreach($element in $array2){ // write array data to HTML } foreach($value in $array3){ // write array data to HTML } What is the ...

Utilizing vue-router-next without a bundler: A step-by-step guide

Previously, the vue-router plugin would automatically mount to the global application instance like this: if (inBrowser && window.Vue) { window.Vue.use(VueRouter); } In Vue 3, this functionality has been restricted. So, how can I access VueRoute ...

Issue encountered while attempting to adjust a date (the modification was incorrect)

I am currently working on developing a calendar feature using Angular. Part of this project involves implementing drag and drop functionality to allow users to move appointments from one day to another. However, I have encountered a strange issue. When at ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

Tips for removing a row without impacting the rest of the rows

I'm currently developing a VueJs parent component with the ability to generate rows dynamically. This component invokes another component responsible for populating two dropdowns using axios - one for categories and the other for subcategories (with t ...

Having trouble accessing env variables from React Component in Next.js?

I recently set up a Next.js project and included an .env file to store environment variables used in my server.js file. However, I am facing an issue when trying to access these variables from a component. Can anyone provide guidance on how to resolve this ...

Can you explain the process of retrieving API information from a component directory with Next.js?

In the components folder, I have created a reusable component that displays user details for those who log into the system in the header section. Currently, I am attempting to utilize getInitialProps with isomorphic-unfetch. static async getInitialProps( ...

The placement of Bootstrap Datepicker is experiencing issues

I have integrated the Bootstrap Datepicker from Eternicode into my ASP.Net MVC website. While the functionality is working well, I am facing difficulty in positioning the datepicker modal using the orientation option mentioned in the documentation and code ...

Creating a custom class implementation in JavaScript and initializing it with a constructor function

Perhaps there is a similar question out there, but I haven't come across it yet and I'm still facing an issue. Here's what I've tried: function createClass(obj) { const constructor = obj.constructor; constructor.prototype = obj; ...

What are the best practices for utilizing databases with both Javascript and JSF frameworks?

I am currently following the recommendations provided by @BalusC, with additional guidance available here. (The reason I'm posting this here is because it's not related to my previous question). My goal is to retrieve data from my database and d ...

How do I retrieve and pass values from multiple inputs in my React application?

I've implemented the <autocomplete> as an input field, and I'm currently troubleshooting my submit method by logging values to the console. Unfortunately, I can only submit empty data to my axios instance without any Traceback errors for gu ...

Retrieve the date one week prior to today's date in Node.js and format it in Mysql style

I need to find the exact date from one week ago in SQL format using Node.js. I attempted a similar solution as described here - How to get yesterday date in node.js backend? but unfortunately it's not working for my specific case. ...

Having trouble with an unexpected value in your Angular2 Service? Don't forget to add

I encountered an error in my Angular2 app: Error: (SystemJS) Unexpected value 'ReleasesService' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Here is my AppModule code: import { NgModule } fr ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...