I recently started using ES6's destructuring assignment syntax and started to get familiar with the concept. I was wondering if it's possible to extract a nested property using the same syntax.
For example, let's say I have the following code:
let cagingIt = { foo: { bar: 'Nick Cage' } };
I know I am able to access extract foo
into a variable by doing:
// where foo = { bar: "Nick Cage" } let { foo } = cagingIt;
However, is it possible to extract a deeply nested property, like bar
. Perhaps something like this:
// where bar = "Nick Cage" let { foo[bar] } = cagingIt;
I've tried finding documentation on the matter but to no avail. Any help would be greatly appreciated. Thank you!
JavaScript destructuring, nested and otherwise, is a nice shorthand to allow us to quickly define variables from values in a collection, object, or array. We can use it with rest syntax to assign remaining elements a variable. We can rename the elements that we pull out to a variable name of our choosing.
No, destructuring will give you a reference. AFAIK, there is no way to configure a destructure to shallow clone at the same time.
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
The basic definition of an object in JavaScript is a container for named values called properties (keys). Sometimes, we need to create an object inside another object. In this case, it's called a nested object.
There is a way to handle nested objects and arrays using this syntax. Given the problem described above, a solution would be the following:
let cagingIt = { foo: { bar: 'Nick Cage' } }; let { foo: {bar: name} } = cagingIt; console.log(name); // "Nick Cage"
In this example, foo
is referring to the property name "foo". Following the colon, we then use bar
which refers to the property "bar". Finally, name
acts as the variable storing the value.
As for array destructuring, you would handle it like so:
let cagingIt = { foo: { bar: 'Nick Cage', counts: [1, 2, 3] } }; let { foo: {counts: [ ct1, ct2, ct3 ]} } = cagingIt; console.log(ct2); // prints 2
It follows the same concept as the object, just you are able to use array destructuring and store those values as well.
Hope this helps!
If you have lodash installed, you can use one of the following:
_.get
var object = { 'a': [{ 'b': { 'c': 3 } }] }; _.get(object, 'a[0].b.c'); // => 3
or if you need multiple keys.
_.at
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; _.at(object, ['a[0].b.c', 'a[1]']); // => [3, 4]
You can also safely pair _.at()
up with with Array destructuring. Handy for json responses.
[title, artist, release, artwork] = _.at(object, [ 'items[0].recording.title', 'items[0].recording.artists[0].name', 'items[0].recording.releases[0].title', 'items[0].recording.releases[0].artwork[0].url' ]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With