Namespace: Objects:clone

Objects:clone

Source:

Methods

clone(target, deepopt, nullable) → {*}

Cloning arbitrary objects, values and structured values is no trivial task in JavaScript. For basic values this can easily be achieved by serializing/deserializing via JSON.parse(JSON.stringify(value)), but for everything not included in the JSON standard, such as nodes, sets, maps, functions and objects with constructors this gets hairy pretty quickly.

This function implements a fairly robust recursive cloning algorithm with circular dependency detection and should be sufficient for 90% of your cloning needs. It can create deep and shallow copies, although I generally presume that you need a deep copy if you are in need of a clone method to begin with. This method handles ordinal values, regexes, dates and htmlelements/nodes, as well as nested structures consisting of arrays, plain objects, simple constructed objects with settable properties, sets, maps and even nodelists.

Be aware of these restrictions:

  • map keys are not cloned since, if you would, you'd lose all access to values, because you would have no valid references
  • cloning a nodelist in a shallow manner results in the original list being empty afterwards, since moving a node reference from one nodelist to another automatically removes the reference from the first, because a node may only appear at exactly one place in a dom tree

If this function does not suffice, have a look at lodash's cloneDeep method, which is a very robust and complete (but large and complex) solution: https://www.npmjs.com/package/lodash.clonedeep

Parameters:
Name Type Attributes Default Description
target *

the object/value to clone

deep Boolean <optional>
<nullable>
true

define if nested objects/values are to be cloned as well or just referenced in a shallow way

Source:
Returns:
the cloned object/value
Type
*
Example
const foo = {foo : 'bar', bar : [new Foobar(1, 2, 3), new Set([new Date('2021-03-09'), new RegExp('^foobar$')])]};
const allNewFoo = clone(foo);
const shallowNewFoo = clone(foo, false);
const thatOneTextAgain = clone(document.querySelector('p.that-one-text'));
thatOneTextAgain.classList.add('hooray');