Keywords: AngularJS | JSON.stringify | $$hashKey
Abstract: This article explores the $$hashKey property added by AngularJS when using JSON.stringify, its purpose for change tracking, and methods to manage it through angular.toJson and track by expressions.
Introduction
When serializing objects in AngularJS using JSON.stringify, developers may encounter unexpected properties like $$hashKey in the output. This phenomenon is common when objects are bound to the $scope and used in directives such as ng-repeat. Understanding the origin and purpose of $$hashKey is crucial for effective JSON handling in Angular applications.
What is $$hashKey?
The $$hashKey property is added by AngularJS to objects as an internal identifier to track changes, enabling efficient DOM updates when object properties are modified. For instance, when an array of objects is bound to $scope and displayed with ng-repeat, Angular adds $$hashKey to each object for change monitoring.
From the user's example, the array initially lacks $$hashKey, but after binding to $scope and serializing with JSON.stringify, the property appears with values like "005", "006", etc., due to Angular's change detection mechanism.
How to Avoid $$hashKey in Serialization
To prevent $$hashKey from appearing in serialized JSON, Angular offers two main solutions:
- Use
angular.toJson(obj)instead ofJSON.stringify(obj): This method strips internal Angular properties like$$hashKeyduring serialization. Example: - Utilize the
track byclause inng-repeat: By specifying a unique property for tracking, Angular avoids adding$$hashKey. For example:
var serializedData = angular.toJson($scope.myArray);
This ensures clean output free from Angular-specific metadata.
<ul>
<li ng-repeat="link in navLinks track by link.href">
<a ng-href="link.href">{{link.title}}</a>
</li>
</ul>
Here, track by link.href uses the href property for change tracking, eliminating the need for $$hashKey. Note that the expression must include the object reference, e.g., link.href, not just href.
Best Practices and Conclusion
While $$hashKey typically doesn't cause issues, it can lead to unexpected behavior when serializing data for APIs or storage. To maintain clean JSON, developers should use angular.toJson for serialization in Angular contexts. Additionally, using track by in repetitive directives optimizes performance and prevents unnecessary properties.
In summary, $$hashKey is an internal Angular mechanism for efficient change detection. Leveraging Angular's built-in tools allows developers to manage serialization effectively without compromising functionality.