#!/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?
FWIW, lodash has a cloneDeep function:
Another solution extracted from the issue on Github that works with any level of nested data, and does not require underscore:
Underscore API reference:
...or in this case, cloning an array. Try this:
The following is an addendum I created after Steve's comment below -thx
A Vanilla JS (or using
_.clone
if wanted) deep cloning recursive helper: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:
Prints:
Yay!
a
is unchanged! I can now editb
to my liking!