Angular.copy when the array has a custom property

Consider the following example:

var ar = [4, 2, 3]; ar.$x = 'something'; var br = angular.copy(ar); console.dir(br); 

br no longer has the $x property, because when copying an array, angular for (;;;) with for (;;;) , which does not see custom properties (if it is repeated using for in , then it will work).

Which of the following should I do?

  • Create an array such as a class, and then assign the property;
  • If this is an error, report angular;
  • Change my code because assigning a property to an array is not good practice;
+5
source share
3 answers

Try angular.merge (). This is a deep copy that includes enumerated 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] 
+5
source

I think this is not an Angular problem. If you invoke such a statement:

 ar.$x = 'something'; console.log(Object.prototype.toString.call(ar)); 

You will see that [object Array] will be registered. This is how the Array.isArray() method works, and, in turn, this is how the Angular copy() method decides how to iterate through the entity passed as an argument. This discovery is crucial. The for ... in loop in an array can lead to some confusion in other cases. The following describes why: Why is using β€œfor ... in” with array iteration a bad idea?

I would advise you to change your code for this particular case.

+2
source

Try using jQuery:

jQuery.extend ([], ar);

 var ar = [4, 2, 3]; ar.$x = 'something'; var br = jQuery.extend([], ar); console.dir(br); 
+1
source

Source: https://habr.com/ru/post/1238389/


All Articles