Object.assign fails to copy properly

Currently delving into the world of VueJS.

I have a Method that is designed to take in an Object as its parameter.

In order to avoid modifying the original Object, I make use of Object.assign() to create a clone of it.

Component.vue

export default {
  // ...
  methods: {
    // ...
    activateEditMode (item) {
      this.editItemIndex = this.travelItinerary.indexOf(item)
      this.editItem = Object.assign({}, item)
      // ...
    }
  }
}

The initial Object at this.roteiroCompleto[0]:

https://i.sstatic.net/7md2U.png

However, when I edit the cloned Object labeled as this.itemEditado:

https://i.sstatic.net/i9TP3.png

the changes also reflect on the original Object this.roteiroCompleto[0].

https://i.sstatic.net/H1sHB.png

I've attempted various methods to prevent this binding issue, such as copying each key and value individually, using .slice(), .map(a=>a), yet nothing seems to work. The connection between the two objects remains intact.

Upon executing console.log(this.itemEditado), the following output is generated:

https://i.sstatic.net/DHBbl.png

Interestingly, in another Vue Component utilizing the same approach, everything operates as intended.

Answer №1

Object.assign creates a shallow copy of keys and values in an object, resulting in references to nested objects or arrays being the same as in the original object.

var x = { a: 10, b: { c: 100 } };
var y = Object.assign({}, x);

y.a = 20;
console.log( x.a, y.a ); // outputs 10 20

y.b.c = 200;
console.log( x.b.c, y.b.c ) // outputs 200 200

To create a deep copy of an object, you can utilize functions like cloneDeep in lodash or resort to methods like

JSON.parse( JSON.stringify( obj ) )
.

It's important to note that the latter method is limited to primitive types supported by JSON.

Answer №2

When encountering issues with data types in object manipulation, consider the following approach

import * as _ from 'lodash';

To create a deep copy of an object:

newObj = _.cloneDeep(oldObj);

Answer №3

Reference provided by MDN

 Utilizing Object.assign for deep cloning: Object.assign(this.editItem, JSON.parse(JSON.stringify(item)))

Answer №4

If you need to make a deep copy of objects in JavaScript in the year 2022, one option is to utilize the structuredClone method.

By using the global structuredClone() function, you can create a thorough duplicate of a specified value through the structured clone algorithm.

Visit MDN structuredClone() for more information

Answer №5

If you don't find it necessary to utilize a library, especially if you're not in need of a deep copy like I was, you can simply achieve the desired result by using the following code:

this.editItem = {...item};

By utilizing the ... operator, you can easily break down the contents of item into its respective keys and values within an object literal (the { }), effectively creating a new object with those key-value pairs.

This approach could potentially be beneficial for individuals who, much like myself, do not require a deep copy. While Object.assign may not work as intended, this method proves to be successful.

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 specified container is not a valid DOM element. (Utilizing Ant Design carousel component in React.js)

Here is a snippet of my code where I am having an issue with my carousel. It seems to be giving me an error message "Target container is not a DOM element" when I try to run the server. I have divided my code into two parts - the first part containing the ...

Adjust the width of the table to scroll horizontally and size down to fit within the

My webpage is structured with a sidebar and content section, using flex display with the sidebar set to 0.15 flex and the content set to 0.85 flex. I want this page to be full width of the viewport. The issue arises when I try to incorporate a table into ...

Kubernetes is incorrectly marking the cron job as completed instead of displaying errors, despite the presence of errors

I am currently working on a cron job that will retrieve an excel file from an SFTP server and upload the data into a MongoDB database. In the event that there are errors in the cron job, such as a failure in the SFTP connection due to credential issues or ...

Utilizing Nuxt JS to leverage injected functions from one plugin within another plugin file

I recently implemented Nuxt JS's inject feature to add a reusable function to my page. However, I'm facing challenges trying to utilize this function in another plugin file. Here's the setup: plugins/utils/tracking.js function setCookiePre ...

Unexpected behavior observed in JavaScript and AJAX functionality

In my web development project, I've decided to incorporate JavaScript and AJAX for the signup form functionality. However, I seem to be facing some challenges as I try to post all the textbox values from the signup form through AJAX. The code snippe ...

Utilize a script to cross-reference coordinates received from the client API with those stored in

Having trouble comparing coordinates between an event in my database and those provided by the user's client API (after approval). The user's coordinates are currently only being logged in the terminal: Here's what I have in guestValidate.j ...

Conditional rendering is effective for displaying a form item based on certain conditions, but it may not be as effective for

I want a textarea element to appear or disappear based on the selected state of the radio buttons before it. If "no" is chosen, the textarea will be hidden, and if "yes" is chosen, the textarea will become visible. <fieldset class="input-group form-che ...

Why am I getting the error "TypeError: Object(...) is not a function" when attempting to integrate Vanilla Tilt with React?

Looking for assistance on implementing Vanilla Tilt in my React application, I have referenced the following example: https://codesandbox.io/s/vanilla-tilt-with-react-n5ptm The code snippet I am working with is as follows: import React, { Component, useEf ...

Exploring Angular 5 Nested Loops Using *ngFor and Chunking

I'm new to Angular and working on fetching a nested For-Loop in chunks. <div *ngFor="let eventChunks of chunks(events,3);"> <div *ngFor="let event of eventChunks" class="card-columns"> <event-item [event]="event"></ ...

Select a checkbox from a dropdown menu

I need help with automatically checking a checkbox when an option is selected from a dropdown menu. Here is an example of the HTML code: <table> <tr> <td> <input type="checkbox" name="check1" />Process 1:< ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

Tips on how to submit a form with appended information in a separate

There is a button labeled NEWFORM to create a new form when clicked. Every form includes a submit button. After clicking the submit button of each form, the values within that particular form are sent via AJAX. The issue arises when a new form is created a ...

I am searching for a tool in ThreeJS that functions similar to AxisHelper, possibly a Helper class or utility

While working with Three.js, I have come across many helpful Helper classes that greatly simplify displaying and modifying the scene. However, there is one particular tool that I am struggling to find again. It is similar to the AxisHelper, but it includes ...

What steps can I take to ensure the legend does not get cropped in angular-google-chart?

I have been trying to implement a Google bar chart using angular-google-chart by referring to the example provided here. However, I am facing an issue where my labels and legends are only partially visible in the image below. How can I display the full tex ...

What could be causing the issue of rows being undefined?

Need help creating a user registration feature with Passport(Local-Signup)? Check out the code snippet below: // config/passport.js // requiring necessary modules var LocalStrategy = require('passport-local').Strategy; // loading the user mode ...

Tips for extracting a specific segment from a URL string

Take a look at the outcome of the console.log below: console.log('subscribe:', event.url); "https://hooks.stripe.com/adapter/ideal/redirect/complete/src_1E2lmZHazFCzVZTmhYOsoZbg/src_client_secret_EVnN8bitF0wDIe6XGcZTThYZ?success=true" I need to ...

What could have occurred if you reassigned setInterval to a variable within the useEffect hook?

Can multiple setInterval functions be defined repeatedly to the same variable in a React hook useEffect? After checking, I found that the variable has a new setInterval id value every time it is defined. However, I am curious if there are any instances re ...

Using Vue 3 to have the ability to include multiple composable instances in a single script tag

Currently in the process of revamping our components that are originally built using the Options API. A key point for refactoring from a code-cut perspective is how we handle our multiple modals, each with their own open/close and boolean logic scattered t ...

Invoking a C++ dll in the renderer process of a Node.js application with Electron using node ffi

As I work on developing a windows application using electron, my goal is to utilize the ffi-napi to invoke C++ .dll methods. However, I am facing a challenge with the "Passing_Dll.js" file, where the label with id "GenName" is not being updated when clicki ...

Is it possible to interpret the camera using radius or diameter instead of the traditional x, y, z coordinates

I've been exploring this scenario where I am trying to figure out if it is possible to move a camera by adjusting the radius and diameter instead of using x, y, z positions (Vectors). Currently, I am working with a cube, but my goal is to introduce a ...