Skip to content

Destructuring & Rest Operator

Destructuring

Destructuring allows you to extract multiple pieces of data from arrays and objects and assign them to variables in a single statement.
áp dụng cho mảng lẫn object
// mảng
const myArr = ['hello', 'hi'];

const [a,b] = myArr;
// tương đương với
const a = myArr[0];
const b = myArr[1];

// object
let myObject = {
firstName: 'Huu',
lastName: 'Nghi'
}

// không work, vì object phải lấy đúng tên key
let {a,b} = myObject;

// destructure đúng
let { firstName, lastName } = myObject;
// tương đương với
let firstName = myObject.firstName;
let lastName = myObject.lastName;

Lưu ý:

Array trả đúng thứ tự
Object phải trả đúng tên Prop
Nếu muốn đổi tên biến sau khi Destructuring:
const note = {
title: 'Meeting Notes',
content: 'Discuss project roadmap',
isPinned: true,
};

// đổi tên 'title' thành 'noteTitle', giữ nguyên biến 'content'
const { title: noteTitle, content } = note;

Ứng dụng trong React

// khi truyền vào object 'props' và lấy ra biến 'title'
function NoteCard (props) {
props.title
}

// thì có thể viết ngắn gọn thành
function NoteCard ( {title} ) {
title
}

Destructuring with Rest Operator

Dùng Spread để lấy ra tất cả các phần của Array hoặc Object.
const notes = [
{ title: 'Meeting Notes', content: 'Discuss project roadmap' },
{ title: 'Grocery List', content: 'Buy milk, eggs, bread' },
{ title: 'Workout Plan', content: 'Push day: Bench, Shoulder Press' },
{ title: 'Recipe Ideas', content: 'Pasta, Salad, Tacos' },
];

const [firstNote, ...otherNotes] = notes;

console.log(firstNote);
// { title: "Meeting Notes", content: "Discuss project roadmap" }

console.log(otherNotes);
// [ { title: "Grocery List", content: "Buy milk, eggs, bread" }, { title: "Workout Plan", content: "Push day: Bench, Shoulder Press" }, { title: "Recipe Ideas", content: "Pasta, Salad, Tacos" } ]

Nested Destructuring

const note = {
title: 'Meeting Notes',
address: { street: 'Yen Do', city: 'Ho Chi Minh' },
tags: ['meeting', 'roadmap', 'planning'],
};

const {
title,
address: {street, city}
tags: [firstTag, ...otherTags],
} = note;

console.log(title, street, city, firstTag, otherTags)

Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.