Consider following example:
var ar = [4, 2, 3];
ar.$x = 'something';
var br = angular.copy(ar);
console.dir(br);
br
does not have $x
property any more, because when copying array, angular iterates with for (;;;)
which does not see custom properties (if it iterated with for in
then it would work).
Which of following shall I do?
If your arrays are not huge, you can use the push() method of the array to which you want to add values. The push() method can take multiple parameters so you can use the apply() method to pass the array to be pushed as a collection of function parameters. let newArray = []; newArray. push.
Explanation : = represents a reference whereas angular. copy() creates a new object as a deep copy.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
Overview. Creates a deep copy of source , which should be an object or an array. This functions is used internally, mostly in the change-detection code. It is not intended as an all-purpose copy function, and has several limitations (see below). If no destination is supplied, a copy of the object or array is created.
Try angular.merge() This is a deep copy that includes enumerable properties.
var ar = [4, 2, 3];
ar.$x = 'something';
var br = angular.merge([], ar);
console.dir(br);
Output
Array[3]
0: 4
1: 2
2: 3
$x: "something"
length: 3
__proto__: Array[0]
I think that it's not an Angular problem. If you call such a statement:
ar.$x = 'something';
console.log(Object.prototype.toString.call(ar));
You will see that [object Array]
will be logged. That is how Array.isArray()
method works, and, in its turn, that is how angular copy()
method decides how to iterate through the entity passed as the argument. This detection is crucial beacuse for ... in
loop on an array can make some confusions in other cases. Here is described why: Why is using "for...in" with array iteration a bad idea?
I would advise you to change your code, for this particular case.
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