How can I rename the target during object destructing?
const b = 6;
const test = { a: 1, b: 2 };
const {a, b as c} = test; // <-- `as` does not seem to be valid in ES6/ES2015
// a === 1
// b === 6
// c === 2
[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b . At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1] ) is created. Then the destructuring of the temporary array occurs: [a, b] = [2, 1] .
When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.
Destructuring in JavaScript is used to unpack or segregate values from arrays or properties from object literals into distinct variables, thus it allows us to access only the values required.
Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.
You can assign new variable names, like shown in this MDN Example
var o = { p: 42, q: true };
// Assign new variable names
var { p: foo, q: bar } = o;
console.log(foo); // 42
console.log(bar); // true
So, in your case, the code will be like this
const b = 6;
const test = { a: 1, b: 2 };
let { a, b: c } = test;
console.log(a, b, c); // 1 6 2
Online Babel Demo
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