Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách deep copy Object trong JavaScript

Deep copy nhân bản mọi object con bên trong. Copy và original không share gì - là bản copy thực sự.

Cách dễ nhất: Convert sang JSON string rồi parse lại. Cách này không copy method/function.

Ví dụ

let obj = { foo: 1, bar: { baz: 'test' } };
let newObj = JSON.parse(JSON.stringify(obj));
obj.bar.baz = 20;
console.log(obj);    // { foo: 1, bar: { baz: 20 } }
console.log(newObj); // { foo: 1, bar: { baz: 'test' } }

Kết quả

{ foo: 1, bar: { baz: 20 } } { foo: 1, bar: { baz: 'test' } }

newObj không thay đổi khi update obj → deep copy thành công.

Các cách khác:

  • structuredClone() (modern, hỗ trợ Date, RegExp, Map, Set, cyclic ref): structuredClone(obj)
  • Lodash cloneDeep: _.cloneDeep(obj)
  • Recursive custom: tự viết đệ quy copy từng level
  • Spread operator: {...obj} chỉ shallow copy (1 level)

JSON method limitations: Mất function, undefined, Symbol, Date→string, RegExp→{}, Map/Set→{}, circular reference → error.