Search code examples
javascriptthree.jsweb-worker

Make object structured cloneable


Is there an automatic way to make an arbitrary JavaScript object structured cloneable by removing all methods from the object?

In my specific usecase I'm creating three.js BufferAttribute objects in a web worker and I want to transfer them to the main thread.

My current approach is to create a new object in the web worker that has the same members as the original object, just without the methods. This object is transferred to the main thread and in the main thread I create a proper three.js BufferAttribute object again and assign the properties to it.


Solution

  • Not automatic, but you can use Object.fromEntries, Object.entries, and filter:

    const objectWithoutMethods = Object.fromEntries(
        Object.entries(originalObject).filter(([k, v]) => typeof v !== "function")
    );
    

    Object.fromEntries and Object.entries are relatively new, but easily polyfilled.