ES6 introduced destructuring, which allows us to unpack data from arrays and objects in to their own variables. You’ll see this a lot in frameworks like React.
Array Destructuring
Let’s first look at examples of array destructuring.
const arr = [5, 10, 15, 20, 25];
const [a, b] = arr;
console.log(a, b); // Ouputs: 5, 10
As you can see, we’ve pulled the first two values from the array in to their own variables. We can also use the Rest operator to put the rest of the values in to a new array.
const arr = [5, 10, 15, 20, 25];
const [a, b, ...rest] = arr;
console.log(a, b, rest); // Ouputs: 5, 10, [15, 20, 25]
Object Destructuring
In the same way we can destructure arrays, we can also destructure objects. The difference is that with arrays we use square brackets and with objects we use curly braces.
const obj = {
paramOne: 'String',
paramTwo: 123,
paramThree: true
};
const {paramOne, paramTwo} = obj;
console.log(paramOne, paramTwo); // Outputs: String, 123
Renaming Object Values
You can rename the variables for a specific object key by using the colon.
const obj = {
paramOne: 'String',
paramTwo: 123,
paramThree: true
};
const {paramOne: p1, paramTwo: p2} = obj;
console.log(p1, p2); // Outputs: String, 123
Setting Default Values
You can also set a default value for an object key in case the object property does not exist.
const obj = {
paramOne: 'String',
paramTwo: 123,
paramThree: true
};
const {paramOne: p1, paramTwo: p2, paramFour: p4 = 'Undefined'} = obj;
console.log(p1, p2, p4); // Outputs: String, 123, Undefined
Rest Operator on Objects
You can also use the rest operator on objects, just as we did with arrays.
const obj = {
paramOne: 'String',
paramTwo: 123,
paramThree: true
};
const {paramOne, ...newObj} = obj;
console.log(paramOne, newObj); // Outputs: String, {paramThree: true, paramTwo: 123}
Nested Destructuring
You can also pull out values that are nested in objects. This syntax gets a bit hairy but it’s worth showing an example.
const obj = {
paramOne: [
{paramTwo: 'String', paramThree: 123},
{paramTwo: 'String', paramThree: 456},
]
};
const {paramOne: [{paramTwo, paramThree}, {paramTwo: p2, paramThree: p3}]} = obj;
console.log(paramTwo, paramThree, p2, p3); // Outputs: String, 123, String, 456
Ugh. I’m not a fan of the above.
Leave a Reply