I was just going through MDN and ECMA specs and trying out some cool little time saving tricks with destructuring in javascript.
Destructuring array based on index
let arr = [10, 20, 30, 40, 50]; let {0: first, 3: forth, ...rest} = arr; console.log(first) // 10 console.log(forth) // 40 console.log(rest) // {1: 20, 2: 30, 4: 50}
Ignore some values from array at a particular position
const [a, , b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // 3
Using dynamic key in destructuring
let ab = { a: 10, b: 20 }; let a = 'a'; let {[a]: aVal} = ab; console.log(aVal) //10
You can even use function call, string template etc in the dynamic key
function getDynamicKey() { return "a"; } let ab = { a: 10, b: 20 }; let {[getDynamicKey()]: aVal} = ab; console.log(aVal) //10
Top comments (3)
@technikhil314 Never came across a case of dnynamic destructuring. Meanwhile, here's my article on ES6 descructuring. Hope it helps you understand better.
Nice article. Thanks for sharing. I didn't get one thing though. Is there any thing wrong in my article? All I am trying to show here is rarely used cases of destructuring I know the common cases very well.
Nope, nothing wrong with your article.