Khi dùng destructuring cho đối tượng, các biến được gán phải có tên đúng chính xác với key có trong đối tượng.
const rectangle = {
width: 20,
height: 10,
area: 200,
}
let { width, height, area, perimeter } = rectangle
console.log(width, height, area, perimeter) // 20 10 200 undefined
Info
Nếu key không tồn tại trong đối tượng thì biến được gán sẽ có giá trị
undefined
(tương tự như đối với mảng).
Alias
Có thể đổi tên trong lúc dùng destructuring:
const rectangle = {
width: 20,
height: 10,
area: 200,
}
let { width: w, height: h, area: a, perimeter: p } = rectangle
console.log(w, h, a, p) // 20 10 200 undefined
Default Values
Sử dụng giá trị mặc định:
const rectangle = {
width: 20,
height: 10,
area: 200,
}
let { width, height, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) // 20 10 200 60
Info
Chỉ khi thuộc tính không có giá trị thì giá trị mặc định mới được dùng.
Nested Objects
Nếu trong object có một object khác, ta sử dụng như sau:
const person = {
name: "Quân",
age: 20,
skills: {
fe: "ReactJS",
be: "NodeJS",
},
}
let { name, age, skills: { fe, be } } = person
console.log(fe) // "ReactJS"
console.log(be) // "NodeJS"
Used as Function Parameters
Dùng các biến trích xuất từ object làm tham số cho một hàm.
Giả sử cho đối tượng sau:
const rect = {
width: 20,
height: 10,
}
Không dùng destructuring:
// Without destructuring assignment
const calculatePerimeter = function(rectangle) {
return 2 * (rectangle.width + rectangle.height)
}
console.log(calculatePerimeter(rect)) // 60
Dùng destructuring:
// With destructuring assigment
const calculatePerimeter = function({ width, height }) {
return 2 * (width + height)
}
console.log(calculatePerimeter(rect)) // 60
Used Loop Variables
Tương tự như mảng, cũng có thể dùng biến destructuring làm biến vòng lặp để lặp qua mảng các object:
const todoList = [
{
task: "Prepare JS Test",
time: "4/1/2020 8:30",
completed: true,
},
{
task: "Give JS Test",
time: "4/1/2020 10:00",
completed: false,
},
{
task: "Assess Test Result",
time: "4/1/2020 1:00",
completed: false,
},
]
for (const { task, time, completed } of todoList) {
console.log(task, time, completed)
}
// Prepare JS Test 4/1/2020 8:30 true
// Give JS Test 4/1/2020 10:00 false
// Assess Test Result 4/1/2020 1:00 false
Related
table tags as Tags, file.cday as Created
from [[Object Destructuring]]
sort file.ctime asc