To create a deep copy of an array of objects in JavaScript you can use methods such as JSON.parse() and JSON.stringify(), or the map() method with the spread operator. These methods can help you to avoid issues with shallow copying and ensure that your code behaves as expected.
let deepCopyArray = JSON.parse(JSON.stringify(originalArray));
JavaScript deep copy array of objects example
A simple example code deep copies an array of objects in JavaScript using the JSON.parse()
and JSON.stringify()
methods:
<!DOCTYPE html>
<html>
<body>
<script>
let originalArray = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Mark" }
];
let deepCopiedArray = JSON.parse(JSON.stringify(originalArray));
// Modify the original array
originalArray[0].name = "Alice";
// Verify that the deep copy is unaffected
console.log(deepCopiedArray[0].name);
console.log(originalArray[0].name);
</script>
</body>
</html>
Output:
Another way to deep copy an array of objects is to use the map()
method. This method creates a new array by calling a function on each element of the original array.
let originalArray = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Mark" }
];
let deepCopiedArray = originalArray.map((obj) => ({ ...obj }));
console.log(deepCopiedArray);
In the above example, we use the spread operator (...
) to create a new object for each element of the original array
Comment if you have any doubts or suggestions on this Js object copy object.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version