javascript - structuredClone with function giving an error - Stack Overflow

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

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()

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()

Share Improve this question edited Mar 28, 2023 at 12:41 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Mar 22, 2023 at 8:26 copenndthagencopenndthagen 50.9k105 gold badges313 silver badges491 bronze badges 1
  • 4 Yep, you can't structuredClone a function. – AKX Commented Mar 22, 2023 at 8:33
Add a ment  | 

2 Answers 2

Reset to default 7

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

structuredClone throwing error in browser, so i found alternate way using lodash npm package

npm i 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744907211a4600328.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信