RSS

jLINQ – LINQ for Javascript

05 May

jLINQ is a very interesting and light-weighting library for writing Linq similar query against arrays of JavaScript objects.

Say you have an object like this:

var records = [ 
   { 
     firstname: "John", 
     lastname: "Smith", 
     age: 25, 
     admin: false, 
     locationId: 4, 
     permissions:["read", "WRITE", "Delete"], 
     lastlogin:new Date("2/24/2008") 
   }, 
   //... and so on... 
 ]; 

To select all records with first name starting with “J” we use the Query Command startsWith with two parameters – field name and value. In the example bellow I select all records from records object where firstname field starts with “J” and puts them in order. It’s possible to specify up to 25 field names for the orderby command. Starting a field name with a “-” will cause it to sort descending.

 
var results = jLinq.from(records)
    .startsWith("firstname", "J")
    .orderBy("admin","age")
    .select();

Each time you call the command it returns the same instance so you can specify multiple conditions and actions that will be performed in chain. For queries with lots of conditions jLINQ offers so called “Command Memorizing”. Consider the following query:

 
var results = jLinq.from(records) 
   .startsWith("firstname","A").or() 
   .startsWith("firstname","B").or() 
   .startsWith("firstname","C") 
   .orderBy("firstname") 
   .select(); 

By the time the or() command is executed jLINQ query already knows what the last command was. With “Command Memorizing” it’s possible to repeat the same command without specifying the field name. All you have to do is change the value of the parameter like this:

 
var results = jLinq.from(records) 
   .startsWith("firstname","A").or("B").or("C") 
   .orderBy("firstname") 
   .select(); 

Or repeat the same command but change field name and field value:

 
var results = $.from(records) 
   .startsWith("firstname","A").and("lastname","B") 
   .orderBy("firstname") 
   .select(); 

There is a whole bunch of useful commands available in jLINQ. For instance, such Query Commands as startsWith/endsWith/contains that checks if the field starts/ends/contains specified value, match command that checks the value against regular expression, less/greater/between and etc.

Advertisements
 
Leave a comment

Posted by on May 5, 2009 in JavaScript

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: