There is some destructuring going on here:
const { [a]: b } = this.props
But, what does [a]: b
do: what does the brackets with colon do?
In my case, a
is supplied as one of the props with a string value.
Destructuring means to break down a complex structure into simpler parts. With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.
Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.
10.1 Overview. Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment). How to extract the values is specified via patterns (read on for examples).
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
This ES6 destructuring syntax is very similar to the new "Enhanced object literals" for defining objects with variable property names, so I think it's useful to see that first:
Pre-ES6, if you wanted to assign a value to an object with a property name that was variable, you would need to write
var obj = {};
obj[variable] = value
That's because while both the dot-notation and the object literal notation require using the actual property name, the obj[prop]
notation allowed you to have a variable name.
ES6 introduced the extended object literal syntax, which included the ability to write
var obj = { [variable]: value }
The same syntax was incorporated in destructuring, which is what your question shows.
The basic destructuring allows assigning variables given literal property names:
First, assigning to a variable with the same name as a property already in the object (docs):
var person = {name: "Mary"};
var {name} = person;
/// name = "Mary"
Second, assigning a variable with a different name than the one already in the object (docs):
var person = {name: "Mary"};
var {name: myName} = person;
/// myName = "Mary"
(Side-note: if you recognize that, in the first example, var {name} = ...
was just short-hand for var {name: name} = ...
, you'll see that these two examples match more logically.)
But what if you don't know which property you want from person
? Then you can use that same new computed-property-name object syntax from above (docs):
var person = {name: "Mary"};
var propName = getPropUserWantToKnowAbout(); // they type in "name"
var {[propName]: value} = person;
/// value = "Mary"
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