ข้ามไปเนื้อหาหลัก

structuredClone() deep copy ที่ถูกต้องกว่า JSON trick

ลืม JSON.parse(JSON.stringify()) ไปได้เลย — structuredClone() รองรับ Date, Map, Set และ type อื่นๆ ได้ถูกต้อง

วิธีเดิมที่หลายคนใช้:

const copy = JSON.parse(JSON.stringify(original));

ปัญหา:

  • undefined หายไปจาก object
  • Date กลายเป็น string
  • Map, Set กลายเป็น {}
  • circular reference โยน error

ใช้ structuredClone() แทน:

const original = {
  date: new Date(),
  tags: new Set(['a', 'b']),
  meta: undefined,
};

const copy = structuredClone(original);
// date ยังเป็น Date ✅, tags ยังเป็น Set ✅, meta ยังเป็น undefined ✅

browser support ครอบคลุมทุก browser หลักตั้งแต่ปี 2022 และ Node.js 17+ ข้อจำกัดอย่างเดียวคือ clone function ไม่ได้ เพราะ function ไม่ใช่ structured-cloneable data