Destructuring
JavaScript ES6 Cheetsheet: Destructuring
Categories:
Destructuring assignment
// Arrays
const [first, last] = ['Nikola', 'Tesla']
// Objects
let {title, author} = {
title: 'The Silkworm',
author: 'R. Galbraith'
}
Defaults
const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
//Result:
//math === 22, sci === 33, arts === 50
function greet({ name = 'Rauno' } = {}) {
console.log(`Hi ${name}!`);
}
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!
Function parameters
function greet({ name, greeting }) {
console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })
Reassign keys
function printCoordinates({ left: x, top: y }) {
console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })
Loop
or (let {title, artist} of songs) {
···
}
Object Deconstruction
const { id, ...detail } = song;
Spread operator Spread
Object Extensions
// with object extensions
const options = {
...defaults,
visible: true
}
// No object extension
const options = Object.assign(
{}, defaults,
{ visible: true })
Array Expansion
// with array extension
const users = [
...admins,
...editors,
'rstacruz'
]
// No array expansion
const users = admins
.concat(editors)
.concat([ 'rstacruz' ])
Extract value
const fatherJS = { age: 57, name: "Zhang San" }
Object.values(fatherJS)
//[57, "Zhang San"]
Object.entries(fatherJS)
//[["age", 57], ["name", "Zhang San"]]