Shallow clone object

OSCC · JavaScript, Object · Sep 15, 2020

Creates a shallow clone of an object.

  • Use Object.assign() and an empty object ({}) to create a shallow clone of the original.
const shallowClone = obj => Object.assign({}, obj);
const a = { x: true, y: 1 };
const b = shallowClone(a); // a !== b

Recommended snippets

  • Deep clone object

    JavaScript, Object

    Creates a deep clone of an object. Clones primitives, arrays and objects, excluding class instances.

  • Pick matching object keys

    JavaScript, Object

    Creates an object composed of the properties the given function returns truthy for.

  • Object from pairs

    JavaScript, Object

    Creates an object from the given key-value pairs.