Object destructuring in Javascript – A cheatsheet

The other day, I was talking to a friend of mine who is a great iOS dev, but was learning JS for… reasons. At some point, he asked about this syntax which was about object Javascript destructuring/destructuring assignments. Over the next few minutes in our chat, I ended up showing in everything (almost, I suppose) that he could achieve with the object destructuring syntax.

Later I thought that this was a cool little thing that someone else might find useful too, and it was in a rather nice to read format as well. Hence, this post. Let’s begin.

The article is broken up in two cases. The only difference is the variable we use for our operations.

Case 1 – Plain old JS object

const x = {
	a: 1,
	b: 2,
	c: 3

// I just want the props `b` and `c`.
const { b, c } = x;

// If I want `a` in a variable, but `b` and `c` in an object, then...
const { a, ...o } = x; // a = 1, o = { b: 2, c: 3 };

// I want the `d`
const { d } = x; // undefined

// I want `d` to have a default value if `x` doesn't have `d`
const { d = 4 } = x; // d = 4

// I want `a`, but with a different variable name `p`
const { a: p } = x; // p = 1

// I want `d` but with a different variable name `p`, and with a default value
const { d: p = 10 } = x; // p = 10

Case 2 – A POJO with a nested prop

const x = {
	a: 1,
	b: 2,
	c: 3,
	d: {
		m: 10,
		n: 11

// I want a child of `d`
const { d: { m } } = x; // m = 10

// I want a child of `d`, with a different name `p`
const { d: { m: p } } = x; // p = 10

// I want a child of `d`, with a different name `p`, and default value 20
const { d: { m: p = 20 } } = x; // p = 10, because x.d.m exists

// I want a child of `x` named `e` which may be an object or not present, with a different name `f`, with a default value of 20
const { e: { m: f = 20 } = {} } = x; // f = 10

As you may have noticed, when trying to access a nested object which may not be present, the destructuring assignment code becomes rather complex and hard to read. This only gets worse with deeper levels of nesting.
I like writing fewer lines of code, but absolutely not at the cost of verbosity, so often I’ll destructure only upto a level or two, and then use some other more readable logic for the rest of the thing.

But there is one thing on the horizon that will solve this pain in one line, in one go. Optionals. But it’s currently in Stage 1, so, it’ll take some time before we can use it out of Babel.

To learn more, and learn about destructuring assignment in general in JS, read this on MDN.

Leave a Reply

Your email address will not be published. Required fields are marked *