DEV Community

Cover image for Cloning JavaScript objects using graph theory
Andrea Simone Costa
Andrea Simone Costa

Posted on

Cloning JavaScript objects using graph theory

Introduction

The JavaScript slang allows us to clone objects in more than one way. We can perform a shallow clone using Object.assign or the spread syntax and a deep clone thanks to the JSON.parse(JSON.stringify()) trick.
Unfortunately, the last solution suffers from a problem: JSON.stringify cannot work on an object that has circular references, erroring out in such a case.

In this episode we'll learn a bit of graph theory to then use this knowledge to build a simple, but efficient, deep cloner.

 

Link to the full article 😄

Discussion (0)