GG. GG. - 1 year ago 314
Javascript Question

Lodash .clone and .cloneDeep behaviors


I try to clone an array of objects with nested objects.

Something like:

var data = [
{ id: 1, values: { a: 'a', b: 'b' } },
{ id: 2, values: { c: 'c', d: 'd' } }


With the
method and the
parameter at

var clone = _.clone(data, true);

data[1].values.d = 'x';

console.log( _.isEqual(data, clone) ); // true, clone[1].values.d == 'x'

I expected
clone[1].values.d == 'd'

If isDeep is true nested objects will also be cloned, otherwise they
will be assigned by reference.

What is wrong?


In addition, when I try with the
method, I get an error:

var clone = _.cloneDeep(data);

// Uncaught TypeError: Object function u(n){return n instanceof u?n:new o(n)}
// has no method 'cloneDeep'

Why this error?


the clone has no reference to the original object as expected:

var clone = $.extend(true, {}, data);

console.log( _.isEqual(data, clone) ); // false, clone[1].values.d == 'd'

Answer Source

Thank you to Gruff Bunny and Louis who helped me with their comments.

In fact, as I use Backbone.js too, I loaded the Lodash Underscore build who disable some extra-features:

var clone = _.clone(data, true);

data[1].values.d = 'x';

console.log( _.isEqual(data, clone) , data , clone );

The description said:

Underscore build (includes the Backbone build which is a subset of the Underscore build)

I don't know exactly what that means.

Actually I just changed the Underscore build by the Normal build into my Backbone application and the application is still working. So I can use the Lodash .clone with the behavior expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download