For usual object using string as key, we can use JSON.parse(JSON.stringify(myObject))
.
Another
How can I deep clone an object using Symbol()
as keys ?
Note: structuredClone({[Symbol()]: 42})
returns {}
which is not usable either
For usual object using string as key, we can use JSON.parse(JSON.stringify(myObject))
.
Another
How can I deep clone an object using Symbol()
as keys ?
Note: structuredClone({[Symbol()]: 42})
returns {}
which is not usable either
2
Answers
Use
Object.getOwnPropertySymbols
to iterate and copy symbols.You can improve the code by copying property descriptors instead of simple property assignment.
One approach would be to iterate through all properties and
Symbols
and copy them to a new object(sincestructuredClone
will not be able to cloneSymbols
andmethods
1).SIDENOTE:
The
clone
andcloneDeep
functions provided by lodash cloneSymbols
in case you’re flexible for using a library to achieve your purpose.