Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6/ES2015 object destructuring and changing target variable

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
like image 280
Jack Allan Avatar asked Jan 20 '16 15:01

Jack Allan


People also ask

How do you swap variables in Destructuring assignment?

[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] .

How do you Destructure an object in ES6?

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.

How do you Destructure parameters?

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.

How do we assign a default value to a Destructured parameter?

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.


1 Answers

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

like image 69
thefourtheye Avatar answered Nov 12 '22 13:11

thefourtheye