Module: util/clone-object

An implementation of a clone function for Javascript objects. This utility module can be used by anyone, there is nothing specific to ONE in it apart from putting in support for the kinds of objects we may need (which is quite exhaustive though, albeit incomplete).

Source:

Methods

(static) clone(objectToBeCloned) → {object}

Parameters:
Name Type Description
objectToBeCloned object

The object to be cloned is not changed by this function

Method for deep-cloning a Javascript object

The use case this was designed to deal with is Javascript objects that are used to hold data, without functions, symbols and non-standard property descriptors.

  • Handles cycles
  • Non-enumerable properties and Symbols are ignored
  • Inheritance, enumerability, getters/setters and function properties were not even considered (the structure returned by Object.getOwnPropertyDescriptors())
  • Handles Arrays and Date objects
  • Handles Map and Set objects but only produces shallow copies of them
  • Handles special values such as NaN, undefined or Infinity
  • Can easily be extended to others (like RegEx)

Alternatives

These alternatives work for simple data-only objects without cycles:

Shallow clones (fastest option!)

const clone = Object.assign({}, obj);

Deep clones

const clone = JSON.parse(JSON.stringify(obj));

JSON.stringify does not work for special values such as Infinity, sparse arrays, NaN, undefined and any built-in objects such as Date and does not deal with cycles and built-in object types such as Date, Map, Set.

Resources

Source:
Returns:

Returns a new object which is a clone of the given object's enumerable properties

Type: object