To inherit properties of one object by another while dealing with JavaScript objects, I often see usage of _.clone
where the intention was to create an object with another object's properties and then it would be extended.
Why can't we just use _.extend
which is more relevant to extend an object?
Please tell me the difference between the two and why we can't _.extend
instead of _.clone
which is a costly operation.
extend lodash method works by assigning the own properties, and prototype properties of one or more objects to an object. Assigning is another term for referencing, rather than copying, or cloning.
Sep 20, 2019. Lodash's clone() function is a powerful utility for shallow cloning generic objects. The Object. assign() function or the spread operator are the canonical methods for shallow copying a POJO.
In order to deep copy an array using Lodash, you can use the _. cloneDeep() method. Note: The _. cloneDeep() method functions by creating a fully independent yet exact copy of supplied values.
assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
_.extend
mutates the object. _.clone
creates a copy by values, not by reference and does not change the original object. Please note that _.extend
is merely an alias for _.assignIn
.
_.assignIn(object, [sources])
Note: This method mutates
object
.https://lodash.com/docs/4.17.2#assignIn
Also see documenation for _.clone
:
https://lodash.com/docs/4.17.2#clone
If you _.extend()
an existing object, you mutate the object. If you _.clone()
it first, the original object remains untouched.
You could of course extend an empty object with the original object's properties and some additional ones, which also leaves the original object unchanged:
_.extend({}, originalObject, {
additionalProperty: "foo"
})
This works very similar to a shallow clone of originalObject
. With ES2015, you can achieve the same goal with plain JavaScript and Object.assign()
.
Additional reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With