What is the best way to duplicate an object and assign it to two variables in Vuex without affecting the original object

I'm facing an issue where I copy an object to two states using the spread operator, but when I make changes in one state, the other state is also affected.

My goal is to implement an edit operation for itemDetails, which contains multiple items fetched upon mounting. The index of the item being edited is passed as editItemIndex. After editing, the item should be replaced.

I attempted to create a duplicate of itemDetails for resetting purposes named oItemDetails, but even the items within oItemDetails are altered after editing.

Please share some suggestions on how to prevent copying by reference.

state: {
    itemDetails: [],
    oItemDetails: [],
    editItem: [],
    editItemIndex: null,
},
actions: {
    async showItemsEditModal ({state, commit}, value) {
      commit('setItemsModalStatus', true);
      state.oItemDetails = await {...value};
      state.itemDetails = await {...value};
    },
    async openEditItemModal ({state, commit}, data) {
      state.editItem = await {...data.data}
      state.editItemIndex = await data.item_index
   },
   async editItem ({state, commit}, data) {
      state.itemDetails.items[state.editItemIndex] = await data
   },
   async resetItem ({state}) {
      console.log(state.itemDetails, state.oItemDetails)
      state.itemDetails = await {...state.oItemDetails}
   }
}

Answer №1

When dealing with deep objects, it is important to perform a deep clone in order to prevent copying references. Instead of using {...value}, consider using lodash clone deep or

JSON.parse(JSON.stringify(value))
.

Keep in mind that the performance of JSON.parse and JSON.stringify may not be optimal. For better results, you can opt for lodash clone deep.

Answer №2

To duplicate an object, you must spread it and save it in a variable, then use the duplicate instead of passing a spread as an argument.

Here is a basic example of duplicating an object:

Take note that the duplicate remains unchanged even after the original object is modified.

const sampleObject = {
  title: "Crystal Silence",
  artist: "Chick Corea"
}

// Duplicate the object

const duplicate = {...sampleObject};

// NOTE: JSON.stringify is used for illustration purposes only

let display = "";
display = "Sample Object before: " + JSON.stringify(sampleObject) +  "<br/>";
display += "Duplicate before: " + JSON.stringify(duplicate) +  "<br/>";

// Now add a new attribute to the sampleObject

sampleObject.album = "Return to Forever";

// Check what happens to the duplicate:

display += "Sample Object after: " + JSON.stringify(sampleObject) + "<br/>" ;
display += "Duplicate after: " + JSON.stringify(duplicate);

const container = document.getElementById("container");
container.innerHTML = display;
<div id="container"></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

The process of sending an array of objects to a Controller Action through a jQuery ajax request in .NET Core 2.2 fails to function as intended

When I stringify an array of objects, the controller action does not receive it and the parameter of the action (the model) is null. I have explored various solutions to this issue on StackOverflow, but none of them have resolved my problem. Here are the ...

The protection ensured by employing an extensive hash in the query string for the recognition of a changing document

I am currently developing a small web application that creates exercise program printouts. The concept is simple - a user like a personal trainer can craft an exercise regimen and send it to their client via email using a unique link. http://www.myurl ...

The functionality of the JQuery Mobile click event may vary depending on the position of the element within the HTML

I am in the process of creating a collapsible-set grid that dynamically displays information when each collapsed grid is clicked. The goal is to perform certain actions to retrieve the desired data and generate HTML code to be inserted dynamically within t ...

how to eliminate a specific item from an array using filtering in a React application

In my current project, I have defined an array in the state like so: this.state = { typeAdded: [] } There are two tables in my application, both with checkboxes. If a user checks a checkbox, I add that value to the array. If the checkbox is unchecked, ...

Experiencing issues with this.$refs returning undefined within a Nuxt project when attempting to retrieve the height of a div element

I am struggling with setting the same height for a div containing Component2 as another div (modelDiv) containing Component1. <template> <div> <div v-if="showMe"> <div ref="modelDiv"> <Comp ...

The jade files are not being detected by gulp.watch()

Out of the blue, my gulpfile.js's watch statement for all of my jade files decided to stop functioning. Any idea why this might be? The Jade task is set up as follows: gulp.task('jade', function() { gulp.src('app/*.jade') . ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

What is the best way to choose a tag from an app within components or views?

In my main component file, I added a color picker input in the navigation section to change the background color of the application. This works fine as the body tag can be accessed easily within the DOM. Furthermore, I store the selected color in local st ...

Troubleshooting problems with callback functionality in conjunction with Expressjs, JWT authentication, and Angular

For my current project, I am implementing authentication using JWT with Expressjs and Angularjs. However, I now need to integrate node-dbox to access Dropbox files of my users. The issue arises when trying to store the token received from Dropbox for user ...

Loading an OBJ file from a blob using three.js

I am currently attempting to load an OBJ file from a blob using Three.js. After referring to this resource and successfully loading STL files, I encountered an issue with loading OBJ files. The error message I received is as follows: TypeError: text.indexO ...

`Javascript often returns NaN for basic calculations`

Hello, I am currently developing a basic calculator for a game but I have encountered an issue. Despite having just started learning this programming language and reading all available tutorials, I am now in the process of writing code to gain more experie ...

Attempting to rename the "like" button in Django Ajax, however encountering difficulties

My button is currently functioning, but it's embedded within a Django for loop. I want to move the JavaScript logic to a separate file, but before that, I need to rename it appropriately. Check out this excerpt from my code: {% for post in posts %} ...

What is the proper way to declare an empty timestamp variable as a global variable so that we can assign a value to it later on?

How can I declare a global timestamp variable with an initial empty value that I can use within my functions and assign values to as needed? For instance, if I have two buttons that each trigger a method: <button (click)="startTime()">Starting time ...

Mandate that users select from the available place autocomplete suggestions exclusively

I have integrated the "Places" Google API to enable address autocomplete in an input field on my website. However, since the service is limited to a specific area, I have implemented an autocomplete filter. The issue I'm facing is that users are stil ...

When executed on the node REPL, lodash.sortBy will update the lodash value

When I access the node REPL, the following happens: > _ = require('lodash'); > // it displays the whole lodash object > _.sortBy(['1234', '123'], function (element) { return element.length; }); > [ '123&apos ...

Browser Compatibility in Three.js

Could someone assist me with activating webgl on Internet Explorer version 8? I am able to use Firefox and Chrome without any issues. Your help would be greatly appreciated. ...

Images with fadeIn-Out effect on a slide restrict the movement of the div

I am currently working on a project where I have a div named "background" containing 4 images (400x300px) that fade in and out in a row every x seconds. The issue I am facing is that these images are displaying on the top-left of the browser, and I am tr ...

Combining selected boxes through merging

Looking to create a simple webpage with the following requirements: There should be 10 rows and 3 boxes in each row. If I select 2 or more boxes or drag a box, they should merge together. For example, if my initial screen looks like this: and then I se ...

What is the best method for eliminating script tags from a Magento web store's source code?

Below is the source code for the Magento site's homepage. I am looking to eliminate all JavaScript links from the code: ...

Using JavaScript/jQuery to send JSON data via POST request and download a file

I am currently developing a single-page web application using jQuery. It communicates with a RESTful web service through AJAX calls. My main goal is to achieve the following tasks: Send a POST request containing JSON data to a RESTful URL. If the reques ...