In my component i have declarated some data like this:
data() {
return {
defaultValue: {json object with some structure},
activeValue: {}
...
And in component methods a make copy this value:
this.activeValue = this.defaultValue
But problem is, after change this.activeValue
value a have changes in this.defaultValue
too.
If i use Object.freeze(this.defaultValue)
and trying change this.activeValue
i have get error - object is not writable.
How i can make copy of data but without reference?
You can simply use copy = Object. create(originalObj); but you may want to use copy = JSON. parse(JSON. stringify(originalObj)); to avoid any reference in sub objects (Deep Copy).
To avoid the overhead, you can use Object. freeze to prevent Vue from making your objects reactive. The example freezes the attributes nested property, which means Vue won't pick up any changes in them.
To get data from a local JSON file, we need to import the file into the component where we want to process the data. We do the import just like we would with a component, except the component name is replaced with whatever we want to call the data set.
To make a “real copy” (a clone) we can use Object.assign for the so-called “shallow copy” (nested objects are copied by reference). For “deep cloning” use _.cloneDeep (obj) from loadash library. Show activity on this post. JSON stringify&parse method have some issues like converting date objects to strings.
When doing a shallow clone on an object that references other objects you copy the references to the external objects instead of cloning them. To clone the object completely do a Deep Clone. For the deep clone, per Evan's suggestion in the first link, one could use: JSON.parse (JSON.stringify (object)).
However, if you use the assignment operator for a reference value, it will not copy the value. Instead, both variables will reference the same object in the memory: And when access the object via the new variable (copiedPerson) and change the value of its property (name), you change the value of the property of the object.
All operations via copied references (like adding/removing properties) are performed on the same single object. To make a “real copy” (a clone) we can use Object.assign for the so-called “shallow copy” (nested objects are copied by reference).
A nicer way rather than using JSON.parse, JSON.stringify is:
this.activeValue = {...this.defaultValue}
but this is not natively supported by some browser (IE), unless used with a transpiler (babel)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Update
Considering your originial question is about a way in Vue, there is also a native method in vue:
this.activeValue = Vue.util.extend({}, this.defaultValue)
as for this answer.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With