1

I have a big object that create charts, containing function, object array etc inside.

I would like to deep copy that object in some situation.

I went online to find a library for deep cloning, and I found only 2

https://www.npmjs.com/package/clone-deep which is a node library and I can't import correctly in my project because it triggers

an only be default-imported using the 'allowSyntheticDefaultImports' flag which I can't change

or lodash.

But it sound very overkill to install a dependency for lodash, and only use the lodash/cloneDeep.

Isn't there something else that would work ? or how to solve the import problem without changing the tsconfig flag.

Bobby
  • 4,372
  • 8
  • 47
  • 103
  • A typescript-only version (I hate that lodash.cloneDeep is littered with globals) can be found here: https://javascript.plainenglish.io/deep-clone-an-object-and-preserve-its-type-with-typescript-d488c35e5574 – Llanfar Jan 31 '22 at 19:35
  • Possibly see https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object/728694#728694 – Paul D. Waite Feb 02 '23 at 23:50

1 Answers1

2

If you don't want to install all of lodash, they have per-method modularized versions, here is the one for clonedeep.

I would also consider installing all of lodash. It has more functions that you may find useful. Some of lodash functions have alternatives already in JavaScript, but you'll see lodash's versions make things much simpler. For example, JavaScript has a sort function, but lodash has sortBy that makes it simpler to sort by a property of an object.

Anyways, if you want a pure JavaScript function to deep clone, I have used this:

const object_b = JSON.parse(JSON.stringify(object_a))

It gets the job done for simple cases, but it will fail with cycles, or with objects that are not serializable to JSON like Set.

Daniel
  • 21,933
  • 14
  • 72
  • 101
  • I know what lodash can do, but installing a lib like that just for one function that I need is overkill. the modularized version is the same as clode-deep, it needs to be imported by using `allowSyntheticDefaultImports` – Bobby Jun 05 '20 at 06:24