Deepcopy in React
You can do, JSON serialisation,
var clone = JSON.parse(JSON.stringify(oldObjCopy));
but, its not recommended as,
you may lose any Javascript, JSON property like Function
or undefined
.Those get ignored by JSON.stringify
, causing them to be missed on the cloned object.
Date
object results into string
.
instead you can use easiest Lodash
,
import cloneDeep from 'lodash/cloneDeep';
var clone = cloneDeep(oldObjCopy);
You can use JSON.stringify
to stringify an object, and use JSON.parse
to parse your result string into an object, you will get your new object same with the one you want to deeply copy.
Example:
let copiedObject = JSON.parse(JSON.stringify(originalObject))
You may be interested in cloneDeep form lodash, used as follows:
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
Heres the npm package for just that method.