การ Clone Object ใน JavaScript
Clone = สร้าง Object ใหม่ที่มี Property เหมือนเดิม มีหลายระดับความลึก
1. Shallow Clone (ระดับผิว - 1 Level)
คัดลอก Property ระดับบนสุด Nested Object ยัง Share Reference เดียวกัน
ก) Spread Operator (ES6) - แนะนำ
const source = {name: 'Salman', age: 23, salary: 25000};
const clone = {...source};
ข) Object.assign()
const clone = Object.assign({}, source);
ค) JSON Method (มีข้อจำกัด)
const clone = JSON.parse(JSON.stringify(source));
ข้อจำกัด: ไม่รองรับ Function, undefined, Symbol, Date, RegExp, Circular Reference, BigInt
2. Deep Clone (ลึก - ทุกระดับ)
คัดลอกทุก Level Nested Object แยก Reference สนิท
ก) JSON Method (Simple Cases)
const deepClone = JSON.parse(JSON.stringify(source));
ข) structuredClone() (Modern, Native, ES2022)
const deepClone = structuredClone(source);
รองรับ: Date, RegExp, Map, Set, ArrayBuffer, TypedArray, Circular Reference
ไม่รองรับ: Function, DOM Node, Symbol (as key)
ค) Lodash cloneDeep (Library)
import { cloneDeep } from 'lodash';
const deepClone = cloneDeep(source);
ตัวอย่างเปรียบเทียบ Shallow vs Deep
const original = {
name: 'John',
address: {city: 'Bangkok', zip: 10100}
};
const shallow = {...original};
shallow.address.city = 'Chiang Mai';
console.log(original.address.city); // 'Chiang Mai' - Mutated!
const deep = structuredClone(original);
deep.address.city = 'Phuket';
console.log(original.address.city); // 'Chiang Mai' - Safe!
สรุปแนะนำ
- Shallow: Spread
{...obj}หรือObject.assign({}, obj) - Deep (Modern):
structuredClone(obj) - Deep (Legacy):
JSON.parse(JSON.stringify(obj))(รู้ข้อจำกัด) - Complex: Lodash
cloneDeep