Quel est le moyen le plus efficace de cloner un objet en JavaScript

Mots clés : javascriptobjectclonejavascript

meilleur 5 Réponses Quel est le moyen le plus efficace de cloner un objet en JavaScript

vote vote

91

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()
var A1 = {a: "2"}; var A2 = Object.assign({}, A1); var A3 = {...A1};  // Spread Syntax 
vote vote

86

JSON.parse(JSON.stringify(obj)) 
var clonedObject = {   knownProp: obj.knownProp,   .. } 
Object.assign({}, obj); 
vote vote

70

var newObject = JSON.parse(JSON.stringify(oldObject)); 
vote vote

65

const clone = structuredClone(original); 
const v8 = require('v8');  const structuredClone = obj => {   return v8.deserialize(v8.serialize(obj)); }; 
const clone = structuredClone(original); 
class StructuredCloner {   constructor() {     this.pendingClones_ = new Map();     this.nextKey_ = 0;          const channel = new MessageChannel();     this.inPort_ = channel.port1;     this.outPort_ = channel.port2;          this.outPort_.onmessage = ({data: {key, value}}) => {       const resolve = this.pendingClones_.get(key);       resolve(value);       this.pendingClones_.delete(key);     };     this.outPort_.start();   }    cloneAsync(value) {     return new Promise(resolve => {       const key = this.nextKey_++;       this.pendingClones_.set(key, resolve);       this.inPort_.postMessage({key, value});     });   } }  const structuredCloneAsync = window.structuredCloneAsync =     StructuredCloner.prototype.cloneAsync.bind(new StructuredCloner); 
const main = async () => {   const original = { date: new Date(), number: Math.random() };   original.self = original;    const clone = await structuredCloneAsync(original);    // They're different objects:   console.assert(original !== clone);   console.assert(original.date !== clone.date);    // They're cyclical:   console.assert(original.self === original);   console.assert(clone.self === clone);    // They contain equivalent values:   console.assert(original.number === clone.number);   console.assert(Number(original.date) === Number(clone.date));      console.log("Assertions complete."); };  main(); 
const structuredClone = obj => {   const oldState = history.state;   history.replaceState(obj, null);   const clonedObj = history.state;   history.replaceState(oldState, null);   return clonedObj; }; 
'use strict';  const main = () => {   const original = { date: new Date(), number: Math.random() };   original.self = original;    const clone = structuredClone(original);      // They're different objects:   console.assert(original !== clone);   console.assert(original.date !== clone.date);    // They're cyclical:   console.assert(original.self === original);   console.assert(clone.self === clone);    // They contain equivalent values:   console.assert(original.number === clone.number);   console.assert(Number(original.date) === Number(clone.date));      console.log("Assertions complete."); };  const structuredClone = obj => {   const oldState = history.state;   history.replaceState(obj, null);   const clonedObj = history.state;   history.replaceState(oldState, null);   return clonedObj; };  main();
const structuredClone = obj => {   const n = new Notification('', {data: obj, silent: true});   n.onshow = n.close.bind(n);   return n.data; }; 
'use strict';  const main = () => {   const original = { date: new Date(), number: Math.random() };   original.self = original;    const clone = structuredClone(original);      // They're different objects:   console.assert(original !== clone);   console.assert(original.date !== clone.date);    // They're cyclical:   console.assert(original.self === original);   console.assert(clone.self === clone);    // They contain equivalent values:   console.assert(original.number === clone.number);   console.assert(Number(original.date) === Number(clone.date));      console.log("Assertions complete."); };  const structuredClone = obj => {   const n = new Notification('', {data: obj, silent: true});   n.close();   return n.data; };  main();
vote vote

60

function clone(obj) {     if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)         return obj;      if (obj instanceof Date)         var temp = new obj.constructor(); //or new Date(obj);     else         var temp = obj.constructor();      for (var key in obj) {         if (Object.prototype.hasOwnProperty.call(obj, key)) {             obj['isActiveClone'] = null;             temp[key] = clone(obj[key]);             delete obj['isActiveClone'];         }     }     return temp; } 

Questions similaires