Logo Peef

📚 Tutoriels 👨🧑🏻‍🏫 Formations 👨🏽‍💻 Experts OdooBientôt 🙋‍♂️ Communautés
À propos de Peef Conditions d'utilisation Sessions de mentorat
Se connecter

How do you clone an object in javascript ?

nuggets 17/03/2021 (18:52) GMT

I usually use :


But it doesn't work well when your object have cyclical references. And the good news is that it doesn't always depend of you.

In the last issue I had, one of my object had a member called 'idSetInterval'. Its value was the value returned by the setInterval() function (the function used to trigger another function call every x milliseconds). This setInterval() function is supposed to return an integer, but in nodejs it returns an object that is part of a doubly linked structure (my code was working pretty well in the browser but not in the backend):

Example of value returned by setInterval() in NodeJS:

Timeout {
  _idleTimeout: 100,
  _idlePrev: [Timeout],
  _idleNext: [Timeout],
  _idleStart: 1742197,
  _onTimeout: [Function],
  _timerArgs: undefined,
  _repeat: 100,
  _destroyed: false,
  [Symbol(refed)]: true,
  [Symbol(kHasPrimitive)]: false,
  [Symbol(asyncId)]: 338,
  [Symbol(triggerId)]: 5

So JSON.stringify doesn't know how to manage cyclical references. I managed this with some hacks, but with doubly cyclical references it is harder.

Do you have a better or simpler method to clone objects in javascript ?



I don't know well but seems here have a good explanation of how you could do it

When reading, the one you used is the fast cloning, take a look at here (the third one maybe) : https://stackoverflow.com/a/122704

There is also this article: https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/

And this one from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

18-03-2021 12:10:14 GMT

Veuillez-vous connecter pour poster un commentaire