Before starting my latest web-development project I was looking for some robust javascript frameworks that I could use.
I was familiar with AngularJS and I loved it, but it doesn’t have a lot of utility methods and I was looking for some solution to solve that problem.
So, I thought about using UnderscoreJS, which is a collection of utility methods with angularJS and I got myself a killer web development toolkit. In this blog post
Using Underscore with Angular:
Combining angular and underscore is pretty straightforward, just add import underscore in your index.html, then add it as a service.
And then we could inject it into our controllers.
Useful Underscore methods:
I have compiled a list of my favourite underscoreJS methods, you can always visit underscorejs.org to view all the methods that are available in underscore.
_.isUndefined:
This method is used to determine whether the specified value is undefined or not, I know you could always do
1 2 3 |
_.isUndefined(value) => (Returns a boolean value true/false) |
_.defaults:
This is also a very useful method, it allows
1 2 3 4 5 6 7 8 |
var data = {"model":"T", "manufacturer": "Ford", "price": "200"}; _.defaults(data, {"model":"N/A", "N/A": "Ford", "price": "0"}) output: ---> {"model":"T", "manufacturer": "Ford", "price": "200"} _.defaults({},{"model":"N/A", "N/A": "Ford", "price": "0"}) output: ---> {"model":"N/A", "N/A": "Ford", "price": "0"} |
_.where:
This method comes handy when you want to search something in the array of objects using some attributes present in the object.
consider the example below.
1 2 3 4 5 |
var data = [{'model':"T", 'manufacturer':'Ford'},{'model':"P", 'manufacturer':'Ford'},{'model':"E", 'manufacturer':'Ford'},{'model':"a", 'manufacturer':'GM'},{'model':"g", 'manufacturer':'GM'}]; So, _.where(list, properties) _.where(data, {'manufacturer':'ford'}) =>[{'model':"T", 'manufacturer':'Ford'},{'model':"P", 'manufacturer':'Ford'},{'model':"E", 'manufacturer':'Ford'}] |
_.uniq:
This method operates on arrays, and it removes duplicates in the array.
Consider the following example:
1 |
_.uniq(array, [isSorted], [iteratee]) |
1 2 |
_.uniq(['Tim','Jon','Jim','Tim']); => ['Tim','Jon','Jim']; |
_.pluck:
if you ever wanted to extract some values from an array of objects, well the pluck method
Here is the example:
1 2 3 4 |
var people = [{name:'Joe', hobby:'baseball'}, {'Jane', hobby:'swimming'}, {'Tim', Hobby:'basketball'}, {'Duke', hobby:'cricket'}]; -.pluck(people,'name'); =>['Joe','Jane','Tim','Duke'] |
By merging these two awesome web development frameworks together we can get a pretty nice web development experience, as angular serves as an awesome MVC, and underscore provides a very useful collection of utility methods.
About me:
I am Mohammed Lakkadshaw. A freelance javascript developer with expertise in NodeJs Angular and React. If you like this article please share them on Twitter Facebook and Google+.