#!/usr/bin/env node var _ = require('underscore'); var a = [{f: 1}, {f:5}, {f:10}]; var b = _.clone(a); b[1].f = 55; console.log(JSON.stringify(a));
This results in:
[{"f":1},{"f":55},{"f":10}]
Clone does not appear to be working! So I RTFM, and see this:
http://underscorejs.org/#clone
Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.
So _.clone
is pretty useless. Is there a way to actually copy the array of objects?
A deep copy is a copy of all elements of the original object. Changes made to the original object will not be reflected in the copy. In this article, you will create deep copies of objects using the Lodash library.
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.
Copy an Object With Object. 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.
Well, there is a trick! If clone does not "clone" nested objects, you can force it to by explicitly cloning each object inside a map call! Like this:
#!/usr/bin/env node var _ = require('underscore'); var a = [{f: 1}, {f:5}, {f:10}]; var b = _.map(a, _.clone); // <---- b[1].f = 55; console.log(JSON.stringify(a));
Prints:
[{"f":1},{"f":5},{"f":10}]
Yay! a
is unchanged! I can now edit b
to my liking!
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