Skip to content

clone()

Eugene Lazutkin edited this page Nov 9, 2020 · 3 revisions

This function creates a clone/copy of a JavaScript object. It can handle objects with circular dependencies.

Introduction

import {clone, equal} from 'deep6';

const a = {a: 1}, b = clone(a);

equal(a, b);                                     // true
Object.keys(a).length === Object.keys(b).length; // true
a.a === b.a;                                     // true
b.a === 1;                                       // true
a !== b;                                         // true

API

clone(a [, options])

Arguments:

  • a — a required argument. It can be anything.

  • options — an optional object. The following optional properties are recognized:

    • circular — a boolean flag. When true, special algorithms are used to detect internal loops in a.
      • It is totally safe to turn it on for all objects, but checks will require more memory and more CPU. In some cases, for performance reasons, you may want to turn it off.
    • symbols — a boolean flag. When true, symbol properties would be clones as well.
      • Normally symbol properties are hidden from enumerating using classical means.
    • allProps — a boolean flag. When true, non-enumerable properties are cloned as well.
    • Any other properties documented in Traverse: clone().

    The default: {circular: true}.

The function returns a cloned copy of a.

Notes

Implemented using Traverse: clone():

import originalClone from 'deep6/traverse/clone.js';

const defaultOptions = {circular: true};
const clone = (a, options = defaultOptions) => originalClone(a, null, options);
Clone this wiki locally