Hermann  Frami

Hermann Frami

1620641812

Calculating Derived Datasets Using Objects As Indexes In AngularJS 1.2.22

At  InVision, when I retrieve data from the server, the payload that’s returned contains all the necessary information for the view. But, it’s not always in the necessary view-model format. As such, I have to generate some degree of client-side data based on the AJAX response. Lately, I’ve been using the JavaScript Object to create derived datasets that I then index based on a look-up key that I’ll have handy in my Angular templates. This pattern has been working really well for me; so, I wanted to put together a quick demo in AngularJS 1.2.22.

NOTE: AngularJS is basically end-of-life (giving way to the modern Angular framework). However, our legacy platform - that my team and I maintain - still runs on AngularJS 1.x. That said, this technique will work just as nicely in modern Angular with TypeScript.

One of the most common data translations that I have to perform is  converting UTC milliseconds into human-friendly date-strings. In our database, as is the de facto standard, all date/time values are stored in the UTC timeszone. When generating AJAX responses, we then serialize those date/time values as UTC milliseconds so that the client-side code can easily render the date/time strings in the user’s local timezone.

In order make this a pain-free operation, I’ll  create an Object  with no prototype:

var dateTranslations = Object.create( null );

Then, I’ll populate this dateTranslations Object using the UTC milliseconds at the look-up key:

dateTranslations[ utcMilliseconds ] = formatDate( utcMilliseconds );

This leaves me with a mapping of date/time values that is indexed by the UTC milliseconds. And now, when I’m rendering my AngularJS template, to output a human-friendly date-string, all I have to do is reference the dateTranslations index:

Created at {{ dateTranslations[ utcMilliseconds ] }}.

More and more, I’ve been using this type of approach, where I have a “raw dataset” that I then either wrap in another, mutable dataset or that I use to then derive additional dataset as with the dateTranslations above. What I’m really loving about this approach is that keeps the underlying dataset in-tact, which is nice for caching; but, I can - at any moment - just regenerate all the derived data.

#javascript / dhtml #angularjs #angular

Calculating Derived Datasets Using Objects As Indexes In AngularJS 1.2.22