Explain Codes LogoExplain Codes Logo

How do you clone an array of objects in JavaScript?

javascript
clone
circular-references
performance
Alex KataevbyAlex Kataev·Dec 13, 2024
TLDR

Deep Cloning an array of objects (all nested objects get fully duplicated) is done using JSON.parse with JSON.stringify:

// less words, more action; deep clone mode activated! const clonedArray = JSON.parse(JSON.stringify(originalArray));

For a Shallow Copy (only the array is new, the objects are the same old buddies you know), the spread operator ... is friendly:

// cloning? more like photocopying, but it gets the job done... const clonedArray = [...originalArray];

The JSON methods say "heck no!" to functions or circular refs; for such complexity, use Lodash's _.cloneDeep:

// Lodash's cloneDeep method, like a Swiss Army Knife of cloning scenarios. const clonedArray = _.cloneDeep(originalArray);

Ascend to the cloning Master Level

Circular References: Round and Round we clone!

For arrays with objects having circular references, the swanky structuredClone function is just what you need:

// handling circular references like a boss with structuredClone! const clonedArray = structuredClone(originalArray);

Bear in mind, it's a newbie API, so a polyfill might come in handy for older browser compatibility.

Run Forest, Run: Performance Mass vs. Class

For performance fans, structuredClone and JSON are more of long-distance runners when deep copying. Need speed over terrain? Use spread operator and .map() for quick cloning of shallow objects:

// Jetpack activated! Fast cloning of shallow objects const clonedArray = originalArray.map(object => ({ ...object }));

Object.assign: Shallow but Fast

If cloning an array with only shallow objects, Object.assign mixed with .map() does the trick:

// Map and Object.assign, the old reliable team! const clonedArray = originalArray.map(object => Object.assign({}, object));

Need a simple array clone double-quick? .slice(0) gets you a quick shallow copy:

// slice and dice, quick and nice const clonedArray = originalArray.slice(0);

Libraries and the Magic Wand

Got complex data structures? Bring in the heavy artillery like Immutable.js or craft your own custom cloning functions to nix recursion issues.

The art of Swift and Deep (Copy)

Ground zero is knowing the difference between deep and shallow copying. Shallow copy is enough when nested objects are just spectator. But, when the game requires a full object tree duplication, deep copying comes into play.

Choose your Cloning Power Ring

While choosing a cloning method, weigh in browser support and data structure's complexity. The right method is a balancing act between performance, compatibility, and the type of objects queued up for cloning.

Shooting Cloning Pitfalls from the Sky

When cloning, track mutable object references like a hawk. Misunderstanding this can drop bugs where one copy’s changes crash land on the other. Also, guard against "too much recursion" errors by smartly avoiding deep copy of huge or complex object architectures.

Custom Cloning: Your Cup of Tea

In specific scenarios, a custom cloning method gives an edge. Here's a custom built clone function that can handle many scenarios, including circular references, functions, and stubbornly non-JSON-serializable objects.

When to Surf Shallow

If the clones aren't set to change, a shallow copy might be all you need. It can save significant processing energy and memory like a power-saving lightbulb.