Saturday 23 December 2017

What is the most efficient way to deep clone an object in JavaScript?





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 =
JSON.parse(JSON.stringify(o));
but question the efficiency.

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
Dates, 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()






See
href="https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/5344074#5344074">Corban's
answer for
benchmarks.





Since cloning
objects is not trivial (complex types, circular references, function etc.), most major
libraries provide function to clone objects. Don't reinvent the
wheel
- if you're already using a library, check if it has an object
cloning function. For
example,








For
completeness, note that ES6 offers two shallow copy mechanisms: href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"
rel="noreferrer">Object.assign() and the href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"
rel="noreferrer">spread syntax.
which copies values of all
enumerable own properties from one object to another. For
example:



var A1 = {a:
"2"};
var A2 = Object.assign({}, A1);


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...