structuredClone() deep copy ที่ถูกต้องกว่า JSON trick
ลืม JSON.parse(JSON.stringify()) ไปได้เลย — structuredClone() รองรับ Date, Map, Set และ type อื่นๆ ได้ถูกต้อง
วิธีเดิมที่หลายคนใช้:
const copy = JSON.parse(JSON.stringify(original));
ปัญหา:
undefinedหายไปจาก objectDateกลายเป็น stringMap,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