Let's say we have an object obj
with its foo
property being non-writable
const obj = {foo: {}}
Object.defineProperty(obj, 'foo', {value: {bar: 'baz'}, writable: false, enumerable: true})
And I want to deep copy this object with its original property descriptors preserved. So for the copied object, its foo
property should still be non-writable.
const propertyDescriptors = Object.getOwnPropertyDescriptors(obj)
const cloned = Object.create(
Object.getPrototypeOf(obj),
propertyDescriptors
)
But the problem occurs when I want to deep copy the foo
property's value. Note that I wrote a recursive algorithm to deep copy but I just used the spread operator here for brevity.
cloned.foo = {...obj.foo}
Now there is an error because cloned.foo
has writable: false
because we preserved the property descriptor from the original obj
I am thinking if there is a way to get around this so that I can deep copy the value of the property and also preserve its original property descriptors?