Useful destructuring snippets
Skip items from an array
const array = [1, 2, 3];
const [a, , b] = array;
Using rest
parameter
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const [a, b, ...c] = array;
console.log(a); // 1
console.log(b); // 2
console.log(c); // [3, 4, 5, 6, 7, 8, 9]
Swap variable values without temp var
let a = 1;
let b = 2;
let [b, a] = [a, b];
Destructure return value of a function
const [a, b] = data();
const { name, role } = data();
Set default values (also works for Objects)
const [a, b=2] = array;
const { first, second='two' } = object;
Get data from an object (also with the rest
parameter)
const user = {
name: 'George',
role: 'SA',
killingZombies: true,
dancing: true
};
const { name, role, ...hobbies } = user;
console.log(hobbies); // { killingZombies: true, dancing: true }
Get data from an object with DIFFERENT variable names
It is also possible to allocate different variable names:
(NOTE: the new name is the 2nd "value" element)
const user = {
name: 'George',
role: 'SA',
killingZombies: true,
dancing: true
};
const { name: namen, role: funktion, ...rest } = user;
console.log(namen) // George
console.log(funktion) // SA
Destruct a function parameter
function ({ name, email, roles }) {
console.log('Name', name);
console.log('Email', email);
console.log('Roles', roles);
}