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

Cách clone (sao chép) object trong JavaScript


Clone Object

Sao chép thuộc tính object này sang object khác để tránh tạo lại object giống hệt. 3 cách phổ biến:

1) Duyệt thuộc tính (cách cũ)

<html> <body> <p id="cloning-1"></p> <script> const sourceObject = {name:"salman", age:23, salary:25000}; let requiredObj = {}; for (let pro in sourceObject) { if (sourceObject.hasOwnProperty(pro)) { requiredObj[pro] = sourceObject[pro]; } } document.getElementById("cloning-1").innerHTML = "targetObject name = " + requiredObj.name + ", age = " + requiredObj.age + ", salary = " + requiredObj.salary; </script> </body> </html>

Kết quả

targetObject name = salman, age = 23, salary = 25000

2) JSON.parse(JSON.stringify()) - Shallow clone

<html> <body> <p id="cloning-2"></p> <script> const sourceObject = {name:"salman", age:23, salary:25000}; let requiredObj = JSON.parse(JSON.stringify(sourceObject)); document.getElementById("cloning-2").innerHTML = "targetObject name = " + requiredObj.name + ", age = " + requiredObj.age + ", salary = " + requiredObj.salary; </script> </body> </html>

Kết quả

targetObject name = salman, age = 23, salary = 25000

Chỉ hoạt động với object "JSON-safe" (không có function, Date, undefined, circular ref).

3) Object.assign() - Shallow copy

<html> <body> <p id="cloning-3"></p> <script> const sourceObject = {name:"salman", age:23, salary:25000}; let requiredObj = Object.assign({}, sourceObject); document.getElementById("cloning-3").innerHTML = "targetObject name = " + requiredObj.name + ", age = " + requiredObj.age + ", salary = " + requiredObj.salary; </script> </body> </html>

Kết quả

targetObject name = salman, age = 23, salary = 25000

Lưu ý: Cả 2 cách 2,3 chỉ làm shallow copy (thuộc tính lồng nhau vẫn tham chiếu chung).