Deep copy array

Source: https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a

JSON.parse and JSON.stringify is the best and simple way to Deep copy

The JSON.stringify() method converts a JavaScript value to a JSON string.The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
// Deep Copy
let a = { x:{z:1} , y: 2};
let b = JSON.parse(JSON.stringify(a));
b.
x.z=0

console.log(JSON.stringify(a)); // {"x":{"z":1},"y":2}console.log(JSON.stringify(b)); // {"x":{"z":0},"y":2}
This is also solution for deep copy objects inside array.
//Deep Clonelet a = [{ x:{z:1} , y: 2}];
let b = JSON.parse(JSON.stringify(a));
b[0].
x.z=0console.log(JSON.stringify(a)); //[{"x":{"z":1},"y":2}]console.log(JSON.stringify(b)); // [{"x":{"z":0},"y":2}]
That’s it. Hope you all get clear understanding of JavaScript Deep copy for array and object. See you :)

Không có nhận xét nào:

StaticImage

  import React , { useEffect , useRef } from "react" import { StaticImage } from "gatsby-plugin-image" impor...