Copying JavaScript Objects
Shallow copy JavaScript arrays or objects while preserving methods and all properties
by Terry Morse
HTML
<h1>Coping JavaScript Objects and Arrays</h1>
<p>A technique to shallow copy (clone) a JavaScript object or array that duplicates the source's methods and non-enumerable properties.</p>
<pre>
function shallowClone(src) {
let dest = (src instanceof Array) ? [] : {};
// duplicate prototypes of the source
Object.setPrototypeOf(dest,
Object.getPrototypeOf(src));
Object.getOwnPropertyNames(src).forEach(name => {
const descriptor =
Object.getOwnPropertyDescriptor(src, name);
Object.defineProperty(dest, name, descriptor);
});
return dest;
}
</pre>
CSS
body {
padding: 0 1rem;
}
pre {
margin: 1rem 0;
padding: 1rem;
border: 1px solid gray;
background-color: #ddd;
}
pre#result {
background-color: #F0F8FF;
}
button {
display: inline-block;
font-weight: 400;
text-align: center;
white-space: nowrap;
vertical-align: middle;
border: 1px solid transparent;
padding: 0.375rem 0.75rem;
font-size: 1rem;
line-height: 1.5;
border-radius: 0.25rem;
color: #fff;
background-color: #007bff;
border-color: #007bff;
}
i {
color: #007bff;
}
JavaScript
function shallowClone(src) {
let dest = (src instanceof Array) ? [] : {};
// duplicate prototypes of the source
Object.setPrototypeOf(dest, Object.getPrototypeOf(src));
Object.getOwnPropertyNames(src).forEach(name => {
const descriptor = Object.getOwnPropertyDescriptor(src, name);
Object.defineProperty(dest, name, descriptor);
});
return dest;
}
class Custom extends Object {
myCustom() {}
}
const source = new Custom();
source.foo = "this is foo";
Object.defineProperty(source, "nonEnum", {
value: "do not enumerate",
enumerable: false
});
Object.defineProperty(source, "nonWrite", {
value: "do not write",
writable: false
});
Object.defineProperty(source, "nonConfig", {
value: "do not config",
configurable: false
});
let clone = shallowClone(source);
console.log("source.nonEnum:",source.nonEnum);
console.log("clone.nonEnum:", clone.nonEnum);
console.log("typeof source.myCustom:",typeof source.myCustom);
console.log("typeof clone.myCustom:",typeof clone.myCustom);