How to remove reference from object in JavaScript

1.7k Views Asked by At

I have an application in ractive.js, and I need to create copy of some data from my component state. example:

const dateGroups = this.get("dateGroups");
this.set("editedPickups.beforeEdit", dateGroups);

And I need to remove reference from "editedPickups.beforeEdit" which is targeted to "dateGroups" because if I change something in "dateGroups" it changes in "editedPickups.beforeEdit" too. I find solution with JSON.stringify and parse, but this object is big and I don't know who this will be acting. This example below not working too:

const dateGroups = Object.assign({}, this.get("dateGroups"));
3

There are 3 best solutions below

1
Krzysztof Woliński On BEST ANSWER

The example you've posted won't work because Object.assign will shallow copy the object (nested props will still hold references to the original object). You can use lodash.cloneDeep().

0
Hiep Le On

You can use spread syntax to create new instant

// if dateGroups is an array
this.set("editedPickups.beforeEdit", [...dateGroups]);
// if dateGroups is an object
this.set("editedPickups.beforeEdit", {...dateGroups});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

0
Zac On

With ES6, you can remove an object reference by using the ... syntax.

const objectWeWantToCopyButNotReference = {
  foo: 'bar'
}

const myNewObject = { ...objectWeWantToCopyButNotReference }

myNewObject.foo = 'not bar'

console.log('my new object has changed:', myNewObject.foo)

console.log('original object not changed: ', objectWeWantToCopyButNotReference.foo)