Miss any of our Open RFC calls?Watch the recordings here! »

clone-deep-circular-references

1.0.0 • Public • Published

clone-deep-circular-references

npm travis Coverage Status minified size minified & gziped size

Recursively (deep) clone JavaScript objects and handles circular references.

This is reimplementation of the package clone-deep to allow have circular references.

Install

Install with npm:

$ npm install --save clone-deep-circular-references

Basic usage

In this way you need to call the cloneDeep function passing as first argument the value to clone.

import cloneDeep from 'clone-deep-circular-references';
 
let obj = { a: 'b' };
let arr = [obj];
let copy = cloneDeep(arr);
obj.c = 'd';
 
console.log(copy);
//=> [{ a: 'b' }]
 
console.log(arr);
//=> [{ a: 'b', c: 'd' }]

Cloning custom classes

By default, if a no plain object is found, no copy will be created, if you want to change it you need to specify true as second argument. Note: in this way the class's constructor will be called with no argument, and then each property will be set.

import cloneDeep from 'clone-deep-circular-references';
 
class MyClass {
    constructor(value) {
        this.prop = value;
    }
}
 
let obj = { a: new MyClass('b') };
let copy = cloneDeep(arr);
 
console.log(obj === copy);
//=> false
 
console.log(obj.a === copy.a);
//=> false

Cloning custom classes

If you want to control how how no plain objects are copied you can specify a function as second argument that copy the value; this function receives as first argument the value to clone and as second argument the a Map with the object already cloned.

Note: if inside this function you want to call the cloneDeep function you need to pass a third argument the map with the object already cloned.

import cloneDeep from 'clone-deep-circular-references';
 
class MyClass {
    constructor(value) {
        this.prop = value;
    }
}
 
let obj = { a: new MyClass('b') };
let copy = cloneDeep(arr, function myCustomClone(value, instancesMap) {
    if (value instanceof MyClass) {
        return new MyClass(value.prop)
    }
    return cloneDeep(value, myCustomClone, instancesMap);
});
 
console.log(obj === copy);
//=> false
 
console.log(obj.a === copy.a);
//=> false

Handled types

The following types are handled recursively by the cloneDeep function:

  • Plain objects
  • No plain objects (see the previous documentation)
  • Arrays
  • Map
  • Set

The other object types are copied using shallow-clone, see the shallow-clone documentation to know what kind of object are handled.

Related projects

You might also be interested in these projects:

License

MIT

Install

npm i clone-deep-circular-references

DownloadsWeekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

9.21 kB

Total Files

5

Last publish

Collaborators

  • avatar