Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การ Destructuring ออบเจกต์โดยยกเว้นคีย์บางตัวใน JavaScript

Rest Destructuring (...rest) ช่วยให้เราแยกคุณสมบัติบางส่วนออกมา และรวมคุณสมบัติที่เหลือทั้งหมดไว้ในออบเจกต์ใหม่ ได้ในบรรทัดเดียว

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Destructuring with Rest</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 18px; font-weight: 500; color: rebeccapurple; }
    .result { color: red; }
  </style>
</head>
<body>
  <h1>Destructuring ออบเจกต์โดยยกเว้นคีย์บางตัว</h1>
  <div class="sample">{"firstName":"Rohit","lastName":"Sharma","age":22}</div>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อ destructuring ออบเจกต์ข้างต้น</h3>
  <script>
    const resEle = document.querySelector(".result");
    
    const obj = {
      firstName: "Rohit",
      lastName: "Sharma",
      age: 22
    };
    
    // แยก firstName ออกมา ที่เหลือเก็บใน restParam
    const { firstName, ...restParam } = obj;
    
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML += `firstName = ${firstName}<br>`;
      resEle.innerHTML += `restParam.lastName = ${restParam.lastName}<br>`;
      resEle.innerHTML += `restParam.age = ${restParam.age}<br>`;
    });
  </script>
</body>
</html>

รูปแบบต่างๆ ของ Destructuring

// Basic
const { a, b } = { a: 1, b: 2, c: 3 };

// Rest - รวมที่เหลือ
const { a, ...rest } = { a: 1, b: 2, c: 3 };
// a = 1, rest = { b: 2, c: 3 }

// Rename - เปลี่ยนชื่อตัวแปร
const { a: newName } = { a: 1 };
// newName = 1

// Default value
const { a = 10 } = { };
// a = 10

// Nested
const { user: { name } } = { user: { name: "John" } };

ผลลัพธ์

แสดง firstName แยกต่างหาก และ lastName, age อยู่ใน restParam object