Clone Objects in JavaScript

在 javascript 裡, 預設 object 的 assign 是直接存取回原物件變數(assign by reference)而不是 assign by value, 會造成內容被修改的問題.

範例:

const obj = { one: 1, two: 2 };
const obj2 = obj;
console.log(
  obj, // {one: 1, two: 2};
  obj2, // {one: 1, two: 2};
);
const obj2.three = 3;
console.log(obj2);
// {one: 1, two: 2, three: 3}; <-- ✅
console.log(obj);
// {one: 1, two: 2, three: 3}; <-- 😱

To clone a JavaScript object correctly, you have 4 different options:

  • Use the spread operator.
  • Call the Object.assign() function.
  • Use JSON parsing.
  • Use the structuredClone() function.
const data = { name: "Max", age: 18 }

// 1
const copy1 = { ...data }

// 2
const copy2 = Object.assign({}, data)

// 3
const copy3 = JSON.parse(JSON.stringify(data))

// 4
const copy4 = structuredClone(data)

附註

  • The 1st and the 2nd approach create a shallow copy.
  • The 3rd and the 4th approach create a truly independent deep copy.

deepClone

work with all types, function and Symbol are copied by reference.

使用 deep copy 的問題會較少, 相關文章:
How to Deep Clone an Array
https://www.samanthaming.com/tidbits/50-how-to-deep-clone-an-array/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *