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' } }
];
_.Clone
With the _.clone
method and the isDeep
parameter at true
:
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?
_.CloneDeep
In addition, when I try with the _.cloneDeep
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?
$.extend
With $.extend
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'
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…