var origin = { a: 1, b: { c: 2, d: 3 } }; // origin object
var copy_obj = { ...origin } // or Object.assign({}, origin.b)
delete copy_obj.b.c; // delete copy object
console.log(origin) // { a: 1, b: { d: 3 } };
I'm studying the invariant nature of things.
However, the above example shows that you want to delete the b.c. element of copy_obj. But the origin is also deleted.
Why is this happening?
A delete marker in Amazon S3 is a placeholder (or marker) for a versioned object that was named in a simple DELETE request. Because the object is in a versioning-enabled bucket, the object is not deleted. But the delete marker makes Amazon S3 behave as if it is deleted.
The effect of removing the delete marker is that a simple GET request will now retrieve the current version ID (121212) of the object.
Amazon S3 Replication is now able to replicate delete markers in S3 buckets. For buckets that use S3 versioning, when a customer issues a delete request without a version ID specified, S3 adds a delete marker on the latest version of the object to protect data from accidental deletions.
When versioning is enabled, a simple DELETE cannot permanently delete an object. Instead, Amazon S3 inserts a delete marker in the bucket, and that marker becomes the current version of the object with a new ID.
Object.assign({}, origin.b)
or spread syntax {...obj}
performs a shallow copy. So the object stored in property b
of origin is not cloned i.e it maintains a reference to the object being nested.
Use the following to make a deep clone.
JSON.parse(JSON.stringify(obj))
var origin = { a: 1, b: { c: 2, d: 3 } }; // origin object
var copy_obj = JSON.parse(JSON.stringify(origin));
delete copy_obj.b.c;
console.log(origin)
Note: This only works for objects that can be serialized
For example:
// Object having functions
const obj= {
a: 1,
b: () => {return 2}
}
const copy = JSON.parse(JSON.stringify(obj));
// property `b` won't be copied as it is a function and can't be serialized.
console.log(copy)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With