Jquery : map and grep functions
Hi friends,
I was going through some utility funcitons being provided by jQuery. Found few methods like grep, map very userful that saves me from writing loops. I could relate them with grep, collect respectively as provided by Groovy, thought would share with you.
I will be taking examples with JSON objects say Student.
grep()
[javascript]
var students = [ {‘id’:1, ‘name’:’amit’},{‘id’:2, ‘name’:’ankit’}];
jQuery.grep(students,function(student){ return student.id>1});
//Output : [{‘id’:2, ‘name’:’ankit’}]
jQuery.grep(students,function(student){ return student.id>1}, true) // invert the results
//Output : [ {‘id’:1, ‘name’:’amit’}]
[/javascript]
[javascript]
var students = [ {‘id’:1, ‘name’:’amit’},{‘id’:2, ‘name’:’ankit’}];
jQuery.map(students,function(student){ return student.name=student.name.toUpperCase()});
//Output : ["AMIT", "ANKIT"]
//Updated students list : [ {‘id’:1, ‘name’:’AMIT’},{‘id’:2, ‘name’:’ANKIT’}];
jQuery.map(students,function(student){ return student.greetings="HELLO " + student.name});
//Output : ["HELLO AMIT", "HELLO ANKIT"]
//Updated students list : [ {‘id’:1, ‘name’:’AMIT’, ‘greetings’ : ‘HELLO AMIT’},{‘id’:2, ‘name’:’ANKIT’, ‘greetings’ : ‘HELLO ANKIT’}]
[/javascript]
Hope this helped.
~~Amit Jain~~
amit@intelligrape.com