Created
March 19, 2019 13:16
-
-
Save jegj/66df8f312bce6271b96ba5dff5c3b76d to your computer and use it in GitHub Desktop.
Basic common tricks based on https://blog.bitsrc.io/6-tricks-with-resting-and-spreading-javascript-objects-68d585bdc83
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const user2 = { | |
id: 200, | |
name: 'Vince Noir' | |
} | |
const user4 = { | |
id: 400, | |
name: 'Bollo', | |
quotes: ["I've got a bad feeling about this..."] | |
} | |
const setDefaults = ({ quotes = [], ...object}) => | |
({ ...object, quotes }) | |
setDefaults(user2) | |
//=> { id: 200, name: 'Vince Noir', quotes: [] } | |
setDefaults(user4) | |
//=> { | |
//=> id: 400, | |
//=> name: 'Bollo', | |
//=> quotes: ["I've got a bad feeling about this..."] | |
//=> } | |
// https://gist.github.com/joelnet/1abc665c56bf94fcf7152642844a9ac9#file-rest-spread-tricks-07-js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const user1 = { | |
id: 100, | |
name: 'Howard Moon', | |
password: 'Password!' | |
} | |
const removeProperty = prop => ({ [prop]: _, ...rest }) => rest | |
// ---- ------ | |
// \ / | |
// dynamic destructuring | |
const removePassword = removeProperty('password') | |
const removeId = removeProperty('id') | |
removePassword(user1) //=> { id: 100, name: 'Howard Moon' } | |
removeId(user1) //=> { name: 'Howard Moon', password: 'Password!' } | |
//https://gist.github.com/joelnet/d8ef09c15d83485cf684e98ca1e55735#file-rest-spread-tricks-05-js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const noPassword = ({ password, ...rest }) => rest | |
const user = { | |
id: 100, | |
name: 'Howard Moon', | |
password: 'Password!' | |
} | |
noPassword(user) //=> { id: 100, name: 'Howard moon' } | |
// https://gist.github.com/joelnet/eee51eee3472bff08ffd064c8ddce202 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment