Khái niệm
Phân rã lồng nhau cho phép trích xuất dữ liệu từ các đối tượng và mảng đa cấp trong một câu lệnh duy nhất. Đây là tính năng mạnh mẽ của ES6 giúp code ngắn gọn và dễ đọc hơn.
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nested Destructuring</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.sample, .result { font-size: 16px; font-weight: 500; margin: 10px 0; padding: 10px; border-radius: 4px; }
.sample { color: #d32f2f; background: #ffebee; }
.result { color: #6a1b9a; background: #f3e5f5; }
button { padding: 8px 16px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #1565c0; }
</style>
</head>
<body>
<h1>Phân rã lồng nhau trong JavaScript</h1>
<div class="sample" id="sample"></div>
<div class="result" id="result"></div>
<button id="btn">PHÂN RÃ</button>
<h3>Nhấn nút để phân rã đối tượng và mảng lồng nhau</h3>
<script>
const sampleEle = document.getElementById('sample');
const resultEle = document.getElementById('result');
const btn = document.getElementById('btn');
// Đối tượng lồng nhau
const obj = {
Name: {
firstName: 'Rohan',
lastName: 'Sharma'
},
age: 22
};
// Mảng lồng nhau
const arr = [22, 33, ['a', 'b']];
// Hiển thị dữ liệu gốc
sampleEle.innerHTML = `Đối tượng: {Name: {firstName: "Rohan", lastName: "Sharma"}, age: 22} <br>`;
sampleEle.innerHTML += `Mảng: [22, 33, ['a', 'b']]`;
// Phân rã đối tượng lồng nhau
const { Name: { firstName, lastName }, age } = obj;
// Phân rã mảng lồng nhau
let a, b, c, d;
[a, b, [c, d]] = arr;
btn.addEventListener('click', () => {
resultEle.innerHTML = `firstName=${firstName} lastName=${lastName} age=${age} <br>`;
resultEle.innerHTML += `a=${a} b=${b} c=${c} d=${d} <br>`;
});
</script>
</body>
</html>
Kết quả
Khi nhấn nút PHÂN RÃ, kết quả hiển thị:
firstName=Rohan lastName=Sharma age=22a=22 b=33 c=a d=b
Lợi ích
- Code súc tích, tránh lặp lại
obj.Name.firstName. - Dễ dàng trích xuất dữ liệu sâu trong cấu trúc phức tạp.
- Tăng khả năng bảo trì và đọc hiểu code.