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

Опубликовано: 01 Октябрь 2024
на канале: Code Samples
20
1

What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but 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.
"structured cloning": https://developer.mozilla.org/en-US/d...
polyfills for existing systems: https://www.npmjs.com/package/@ungap/...
this answer: https://stackoverflow.com/questions/1...
Corban's answer: https://stackoverflow.com/questions/1...
cloneDeep: https://lodash.com/docs#cloneDeep
lodash.clonedeep: https://www.npmjs.com/package/lodash....
clone: https://ramdajs.com/docs/angular.copy: https://docs.angularjs.org/api/ng/fun...
jQuery.extend(true, { }, oldObject): https://api.jquery.com/jquery.extend/...
just-clone: https://www.npmjs.com/package/just-clone