![]() |
VOOZH | about |
Cloning an object refers to creating a copy of an existing object. This is particularly useful in JavaScript to avoid unintentional mutations of the original object. Lodash provides various methods for cloning objects, allowing for shallow or deep copies depending on the use case.
Below are the following approaches to clone an object with Lodash:
Table of Content
_.assign() MethodThe _.assign() method creates a shallow copy of an object by copying its enumerable properties to a target object.
_.assign(target, ...sources)Example: This shallowClone contains the same properties as the original object. However, since it’s a shallow copy, the nested object b still references the same object in memory as original.b. Thus, modifying shallowClone.b.c also changes original.b.c.
Output:
{ a: 1, b: { c: 2 } }
3
_.cloneDeep() MethodThe _.cloneDeep() method creates a deep clone of the value, ensuring that all nested objects are also cloned.
_.cloneDeep(value)Example: In this the deepClone is a completely independent copy of the original object. Changes to nested properties in deepClone do not affect the original, demonstrating that the deep clone successfully duplicated all levels of the object.
Output:
{ a: 1, b: { c: 2 } }
2
_.pick() Method The_.pick() method creates a shallow clone of an object, selecting specific properties to include in the new object.
_.pick(object, [paths])Example: In this the pickedClone contains only the properties a and c from the original object, omitting property b. This operation remains a shallow copy, meaning that if any of the picked properties were objects, they would still reference the same instances as in the original.
Output:
{ a: 1, c: 3 }_.merge() MethodThe_.merge() method merges two or more objects, performing a deep clone of the properties being merged.
_.merge(target, ...sources)Example: In this the mergedClone combines properties from target and source. The nested object b in target is deep-cloned and combined with the nested object b from source, resulting in a new object that includes both properties c and d.
Output:
{ a: 1, b: { c: 2, d: 3 } }