Skip to content
youhoc
  • Pages
    • Home
    • Modern App Guidelines
    • Linux
      • Day 1: Linux Distributions & Navigation
      • Day 2: User Management
      • Day 3: File Permission & Ownership
      • Day 4: Package Management
      • Day 5: Services Management
    • Javascript
      • JS The Weird Part
        • Execution Context
        • Types & Operators
        • Objects & Functions
        • Error Handling & Strict Mode
        • Typescript, ES6, Tra
      • Modern JS
        • JS in the Browser
        • Data Storage JSON
        • Modern JS
        • Advanced Objects & Methods
        • Webpack & Babel
        • Async
      • jQuery
        • In-depth Analysis of jQuery
      • React-ready JS
        • Arrow Function
        • Template Literals
        • Logical AND, OR, Ternary, Nullish Operators
        • icon picker
          Destructuring & Rest Operator
        • Array Method
        • Immutability and Spread Operator
        • Promises, Async/Await, Callback
    • PHP
      • gruntJS
      • composer
      • MySQL
    • Docker
      • Container Basics
      • Container Networking
      • Container Image
      • Container Volume & Persistent Data
      • Dockerfile
      • Docker Compose
      • Docker Registry
    • Node.js
      • 1. Installing & Exploring
      • 2. Core Modules
      • 3. Get User Input
      • File System & Input Arguments
      • 5. Express Web Server
      • 6. Deploy to Heroku & Github
      • Authentication
      • 7. Databases
      • 8. Rest API
    • ReactJS
      • React from Andrew
        • Summary from Next
        • 1. Basics
        • 2. React Components
        • 3. Webpack
        • 4. Styling with SCSS
        • 5. React Router
        • 6. React Hook
      • Modern React From The Beginning
        • Intro to JSX
        • Vite Build Tools
        • Basic Component Creation
        • Component State
        • Props & Component Composition
        • useState with Inputs & Form Submission
        • useEffect, useRef & Local Storage
        • Async / Await and Http Request in React
        • React Router: Declarative Mode
        • ContextAPI
        • React Router: Framework Mode
          • File-routing & HTML Layouts
          • Server-side Data Query
          • Links & Navigation
          • Loaders
    • Typescript
      • Type User vs UserProp
    • Payload CMS

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 ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.