Today I Learned - Rocky Kev

TIL Deleting Object Properties and Shallow Copy

POSTED ON:

TAGS:

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:

TIL why you should always use textContent

Today I learned the difference between 'Node.textContent'. It handles all elements, even hidden ones. It also prevents XSS attacks since it strips tags.

TIL prepend

When you're creating new elements in Javascript, you want to attach the new element to something that exists in the DOM already. You do that with append, and prepend.

TIL the simulating a Pipe function

It’s a pipe function that allows you to chain multiple operations together by taking a series of functions as arguments and applying them in a specific order to the input.