Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.copy when array has custom property

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?

  1. Create array like class and then assign property;
  2. If it's bug, report to angular;
  3. Change my code, because assigning property to array is not good practice;
like image 842
karaxuna Avatar asked Dec 16 '15 15:12

karaxuna


People also ask

How do I copy from one array to another in TypeScript?

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.

Is angular copy a deep copy?

Explanation : = represents a reference whereas angular. copy() creates a new object as a deep copy.

How do you clone an array in Javascript?

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.

What is use of angular copy?

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.


2 Answers

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]
like image 145
Anthony Patton Avatar answered Oct 26 '22 18:10

Anthony Patton


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.

like image 34
Alexandr Lazarev Avatar answered Oct 26 '22 17:10

Alexandr Lazarev