First, let’s write a trivial transformer function that looks very symmetrical, like this:
At first glance, it may seem like this function does nothing. Let’s run it against an object:
It returns the same object that it received. Let’s now feed it with a more complex object:
Now we see that this transformer function returns a new object with only the
fruit attribute present.
So how does it work? This
extract is a lambda function that accepts an object with a
fruit property (left part of the expression). It returns an object with the same
fruit property (right part of the expression) and the same value, disregarding all other properties. The
=> symbol separates the arguments from the lambda function body.
The body of the
wrongExtract function contains just a single expression — the
Now let’s use destructuring to extract some deeply nested data. We want to get a fruit from a box that’s itself located inside a container:
We’ve just written a function to extract a deeply nested structure from the object, using destructuring.
But destructuring is useful not only for extracting the data. Let’s use it to exchange values of two deeply nested attributes of an object. The object is a bit more complicated here, so we won’t try to write the function as a one-liner — formatting it across multiple lines should improve readability:
Still, there’s a lot to digest here. We have a complex object with two (boolean) attributes on different levels of nesting. We want to exchange the values of those attributes, so we destructure them to the
Using these variables, we return a new object with the same structure, but with these attribute values exchanged.
Finally, let’s use array destructuring to make an (opinionated) extraction of an element from an array:
I think the way you can use arrow functions and destructuring assignment for object transformation is pretty cool. There could be of course many more use cases for destructuring, but this is my favorite use case so far.