ES6 Nested Destructuring
I picked this up a while ago on Twitter, use it all the time in my React code, and wanted to document it here. If you're destructuring a JS object like this:
const { username, zip } = props.user;
A valid (and slightly better, in my opinion) refactor is this:
const { user : { username, zip } } = props;
As you add more destructured variables pulled from props
, the object you're referencing stays the same.
Note that this doesn't define user
-- if that's something you want, you have to destructure it on its own:
const { user, user : { username, zip } } = props;
While a little more verbose, I still think this makes for more maintainable destructuring long-term.
Tweet