Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a key for an object inside a replicated object also deletes existing objects

Tags:

javascript

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?

like image 519
박한빈 Avatar asked Jun 26 '20 16:06

박한빈


People also ask

What happens if you delete a delete marker in S3?

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.

What happens when you delete a delete marker?

The effect of removing the delete marker is that a simple GET request will now retrieve the current version ID (121212) of the object.

Are deletes replicated in S3?

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.

What will happen if a user deletes an S3 object where versioning is enabled?

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.


1 Answers

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)
like image 89
Subesh Bhandari Avatar answered Sep 21 '22 12:09

Subesh Bhandari