-4

I want to do a deep copy of an object which also has function as keys.

So I do

deepCopy = structuredClone(existingObjWithFns);

However when this runs, I get the below error:

Uncaught (in promise) DOMException: Failed to execute 'structuredClone' on 'Window': function MyFunction()

halfer
  • 19,824
  • 17
  • 99
  • 186
copenndthagen
  • 49,230
  • 102
  • 290
  • 442

2 Answers2

3

Function objects cannot be duplicated by the structured clone algorithm; attempting to throws a DataCloneError exception.

for more information, you can read MDN

if you want to deep clone nested objects, you should make a function to check the type of all of them and copy them one by one.

Lodash deepClone work with all types, function,s and Symbol copied by reference I suggest that you use Lodash.

but with the object.assign() you can do it faster:

const target = { a: () => { return 1 }, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// Expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget === target);
// Expected output: true

for more information about object cloning you can follow this link

asmanp2012
  • 340
  • 2
  • 11
-1

structuredClone is not available on Browsers stack or on plain javascript. It is a latest feature of Nodejs.

Best way on Browser or plain javascript is to use Lodash.

const _ = require('lodash');
   
var obj = {
    anyField: 23
};
   
// Here is structured clone so it won't get copied
var deepCopy = _.cloneDeep(obj);
   
console.log('Comparing original with'
    + ' deep ', obj === deepCopy);
   
obj.anyField = 10; // Changing original value
   
console.log('After changing original value');
   
console.log("Original value ", obj);
   
console.log("Deep Copy value ", deepCopy);
Rohit Parte
  • 3,365
  • 26
  • 26