Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active August 18, 2021 12:32
Show Gist options
  • Save magnetikonline/4863ce9af8b676c782180eaf6a34d80a to your computer and use it in GitHub Desktop.
Save magnetikonline/4863ce9af8b676c782180eaf6a34d80a to your computer and use it in GitHub Desktop.
Rudimentary JavaScript object deep copy.

Rudimentary JavaScript object deep copy

Function to perform a deep copy of an object - rudimentary in that it will only handle the following types:

  • Primitives
  • Array
  • Object

Basically can perform the following, but also copy undefined:

const clone = JSON.parse(JSON.stringify(myObj));

Also will handle circular references from the item source, such as:

const source = {
	one: 1,
	two: 2,
};

source.three = source;
const clone = copy(source);
'use strict';
function copy(item,seen = new WeakMap()) {
// primitive type?
if (!(item instanceof Object)) {
return item;
}
// property already cloned?
if (seen.get(item)) {
// return prior clone - avoid circular references
return seen.get(item);
}
if (Array.isArray(item)) {
// array type
const clone = [];
seen.set(item,clone);
for (const value of item) {
clone.push(copy(value,seen));
}
return clone;
}
// `{}` type
const clone = {};
seen.set(item,clone);
for (const key of Object.keys(item)) {
clone[key] = copy(item[key],seen);
}
return clone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment