nuggets Publié le 17/03/2021 (18:52) GMT

I usually use :

JSON.parse(JSON.stringify(objectToClone))

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 ?

 

Vous avez besoin d'Experts certifiés pour votre Projet ? Voici comment nous pouvons vous aider :

Odoo Consulting

Nous vous proposons notre expertise technique et fonctionnelle pour que votre système Odoo fonctionne selon vos exigences

Réservez votre accompagnement

Experts IT Certifiés

Vous avez besoin d'Experts IT pour concrétiser votre vision ou rejoindre votre entreprise ?

Découvrez tous les profils ici

Qui sommes-nous ?

Besoin d'en savoir plus sur Peef et les services que nous offrons ?

C'est par là