How to copy json object without reference in vue? How to copy json object without reference in vue? json json

How to copy json object without reference in vue?


If you have simple object, quickest and easiest way is to just use JSON.parse and JSON.stringify;

const obj = {};const objNoReference = JSON.parse(JSON.stringify(obj));


this.activeValue = { ...this.defaultValue }

Using an ES6 spread operator will help you to do a copy if you do not have a nested object. If you equate using equal = sign, it will not create a new object, it will just create a variable with the reference to the current object (like a shallow copy).

To do a complete deep copy, even it is nested object, go for this:

 const objNoReference = JSON.parse(JSON.stringify(obj));

as suggested by Owl.

Click to read more for better understanding of the concept


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!