What is the most efficient way to clone a JavaScript object? I've
seen obj = eval(uneval(o));
being used, but href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval"
rel="noreferrer">that's non-standard and only supported by
Firefox.
I've done things like obj =
but question the efficiency.
JSON.parse(JSON.stringify(o));
I've also seen recursive copying functions with various
flaws.
I'm surprised no canonical solution
exists.
Answer
It's called
"structured cloning", works experimentally in Node 11 and later, and hopefully will land
in browsers. See href="https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/10916838#10916838">this
answer for more
details.
If you do not use
Date
s, functions, undefined
,
Infinity
, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas,
sparse Arrays, Typed Arrays or other complex types within your object, a very simple one
liner to deep clone an object
is:
JSON.parse(JSON.stringify(object))
class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">
class="snippet-code">
const a = {
string: 'string',
number: 123,
bool: false,
nul: null,
date: new Date(),
// stringified
undef: undefined, // lost
inf: Infinity, // forced
to 'null'
re: /.*/, //
lost
}
console.log(a);
console.log(typeof
a.date); // Date object
const clone =
JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof
clone.date); // result of
.toISOString()
No comments:
Post a Comment