0

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"));
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
programmer
  • 550
  • 2
  • 4
  • 25
  • You can use [`lodash.cloneDeep()`](https://lodash.com/docs/4.17.15#cloneDeep) to clone all references recursively – Harun Yilmaz Jul 21 '20 at 12:56
  • 1
    Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Heretic Monkey Jul 21 '20 at 12:56
  • As far as removing the reference, I don't know ractive, but `this.set("editedPickups.beforeEdit", null);` seems like a reasonable attempt. – Heretic Monkey Jul 21 '20 at 12:59
  • Object.assign should work. Stringfly and parse works fast, its good for big, nested object – Arturas Lapinskas Jul 21 '20 at 13:01

3 Answers3

1

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().

Krzysztof Woliński
  • 328
  • 1
  • 2
  • 12
  • Yup. Probably u are right with this, cuz I have other nested object assigned there. I will come back here with an information – programmer Jul 21 '20 at 13:03
1

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

Hiep Le
  • 323
  • 2
  • 13
-1

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)
Zac
  • 1,719
  • 3
  • 27
  • 48