javascript_clone_object
https://www.freecodecamp.org/news/clone-an-object-in-javascript/
javascript_clone_object
解決javascript Clone Object 是否為 reference or value 問題
錯誤示範
不要直接使用 = 來賦予值,因為他是 reference types
,會導致資料跟預想的不一樣
const userDetails = {
name: "John Doe",
age: 14,
verified: false
};
const newUser = userDetails;
console.log(newUser); // {name: 'John Doe', age: 14, verified: false}
const newUser = userDetails;
newUser.name = "Jane Doe";
console.log(newUser); // {name: 'Jane Doe', age: 14, verified: false}
// 這邊連原本的userDetails 也跟著修改了
console.log(userDetails); // {name: 'Jane Doe', age: 14, verified: false}
三種方法
Spread Operator
Shallow Clone
// Declaring Object
const userDetails = {
name: "John Doe",
age: 14,
verified: false
};
// Cloning the Object with Spread Operator
let cloneUser = { ...userDetails };
console.log(cloneUser); // {name: 'John Doe', age: 14, verified: false}
Object.assign
Shallow Clone
// Declaring Object
const userDetails = {
name: "John Doe",
age: 14,
verified: false
};
// Cloning the Object with Object.assign() Method
let cloneUser = Object.assign({}, userDetails);
console.log(cloneUser); // {name: 'John Doe', age: 14, verified: false}
JSON.parse()
Deep Clone
但是會遇到欄位是undefined的時候無法正確轉換
// Declaring Object
const userDetails = {
name: "John Doe",
age: 14,
verified: false
};
// Cloning the Object with JSON.parse() Method
let cloneUser = JSON.parse(JSON.stringify(userDetails));
console.log(cloneUser); // {name: 'John Doe', age: 14, verified: false}
釐清重點
Spread Operator、Object.assign 都屬於 Shallow Clone,
JSON.parse() 屬於 Deep Clone
用錯Clone方法會導致資料的結果跟預期的不一樣
Shallow Vs Deep Clone
Shallow 只複製第一層,資料結構有第二層以上的話又會變成 reference type
Deep Clone:完整Clone,不管幾層都會複製
使用時機
- 確認要複製的資料結構未來是否會有兩層以上的問題
- Json.parse()未必是一個好的解法,文章作者有推薦 Lodash
- 千萬別直接 const cloneuser = userdetail。因為他是reference type