Sometimes we may get an Object with an Array on the parameter. We can use Object and Array destructuring together for the function parameter.
Version
ECMAScript 2015
Traditional Way
let data = {
names: ['Sam', 'Tome', 'Ken']
}
let f = x => {
let name = x.names[0]
return 'Hello ' + name
}
f(data) // ?
- Use
.
and[]
to get value of an Object with an Array
Object and Array Destructuring
let data = {
names: ['Sam', 'Tome', 'Ken'],
}
let f = ({ names: [name, _] }) => {
return `Hello ${name}`
}
f(data) // ?
- Use Object Destructuring to destructure the property of the Object
- Use Array Destructuring to destructure to the element of the Array,
_
for ignoring elements
Conclusion
- We can use Object Destructuring and Array Destructuring together for Function Parameter