DEV Community

Discussion on: The Most Efficient Ways to Clone objects in JavaScript

Collapse
 
coulson84 profile image
Joe Coulson

Native deep cloning is available in the browser. You just have to hack your way to it. The below pseudo-code gives the general idea... It might work but was just typed out here so maybe has typos ? 🤷‍♂️ (You can also use window.postMessage if you're on an ancient browser without MessageChannel support)


function clone(toClone) {
  return new Promise((yay, nay) => {
    const { port1, port2 } = new MessageChannel();

    port1.onmessage = ({ data }) => yay(data);
    port2.postMessage(toClone);
  });
}

clone({a:1}).then(a => console.log(a));
Enter fullscreen mode Exit fullscreen mode