Last active
November 20, 2019 10:46
-
-
Save n3dst4/a7e06f7416e12148ad41205604bbe976 to your computer and use it in GitHub Desktop.
Destructuring tricks in JS or TS
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
// we'll be playing with this happy little object in these examples | |
const foo = { | |
bar: 1, | |
baz: 2, | |
corge: 3, | |
}; | |
// 1. basic destructuring | |
{ | |
const { bar } = foo; | |
// bar === 1 | |
} | |
// 2. destructuring with a "rest" param | |
{ | |
const { bar, ...rest } = foo; | |
/// bar === 1, rest === { baz: 2, corge: 3 } | |
} | |
// 3. destructuring and renaming one of the members | |
{ | |
const { bar: wibble } = foo; | |
// wibble = 1 | |
} | |
// 4. destructuring with a "rest" param and throwing one of | |
// the results into a hole (calling _ a "hole" is borrowed from other languages | |
// where hole is actually a thing - in JS/TS we just use the convention that _ | |
// is where you can put something you want to ignore) | |
{ | |
const { bar: _, ...rest } = foo; | |
// rest === { baz: 2, corge: 3 } | |
// _ also exists but by convention we ignore it | |
} | |
// 5. dynamically destructuring using a key stored in a variable | |
{ | |
const key = "bar"; | |
const { [key]: val } = foo; | |
// val === 1 | |
} | |
// 6. dynamically destructuring into a hole to make an object with | |
// one member deleted | |
{ | |
const key = "bar"; | |
const { [key]: _, ...rest } = foo; | |
// rest === { baz: 2, corge: 3 } | |
/* | |
// why would this be useful? here's a real example from a redux | |
// reducer, removing one member from a collection called "popouts" | |
// based on an id in the action | |
const {[action.payload.frameId]: _, ...popouts} = state.popouts; | |
return { | |
...state, | |
popouts, | |
}; | |
*/ | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment