While working on an Angular application, I ended in a situation where I had to add another tool in my toolbox: underscore.js. It not only offers over 100 functions that support functional helpers like map, filter, invoke — but also has a fluent API that allows to create LINQ style queries.
An example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"orders":[ | |
{"id":1, "description":"order 1", "orderDetails":[{"nr":1},{"nr":2}]}, | |
{"id":2, "description":"order 2", "orderDetails":[{"nr":3},{"nr":4}]}, | |
{"id":3, "description":"order 3", "orderDetails":[{"nr":5},{"nr":6}]}, | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var orderDetails = _ | |
.chain(orders) | |
.pluck('orderDetails') | |
.flatten() | |
.unique(function (orderDetail) { return orderDetail.nr; }) | |
.sortBy(function (orderDetail) { return orderDetail.nr; }) | |
.value(); |