TIL Deleting Object Properties and Shallow Copy
POSTED ON:
TAGS: js
I wanted to loop through a object, but ignore a few object properties.
This is just an example:
const theObject = {
'James' : 20,
'Sarah' : 20,
'Steve' : 40,
'Bill' : 30,
};
I wanted to remove Sarah
, so the For...in loop would be a lot cleaner.
You can use the delete operator.
delete theObject['Sarah']
BUT, this will mutate theObject, and Sarah will be gone forever.
Well, you can copy it.
// WRONG WAY
// since it passes it by reference
// this will delete Sarah from passByReferenceObject AND theObject
const passByReferenceObject = theObject;
delete passByReferenceObject['Sarah'];
// PROPER WAY
// This is making a shallow copy
// And will delete Sarah only from the copy
const copyOfObject = Object.assign({}, data);
delete copyOfObject['Sarah']
If there were nestled objects, going into the deep copy is a better method.
REF:
https://www.javascripttutorial.net/object/3-ways-to-copy-objects-in-javascript/
Related TILs
Tagged: js